dongxian5735 2014-10-27 06:07
浏览 175
已采纳

从html表单添加和删除元素的最佳方法

I want to create a simple html form with different inputs element. The questions and the possible choices for each question are stored in a database. The idea is to render form and child input elements with PHP, so a simple PHP function will take care of typesetting according to whether is type="text" or type="radio":

<form>
First name: <input id="1" type="text" name="firstname">
Last name: <input id="2" type="text" name="lastname">
<input id="3" type="radio" name="sex" value="male">Male
<input id="4" type="radio" name="sex" value="female">Female
<div id="div_5_optional">
Maiden name: <input id="5" type="text" name="maidenname" disabled="disabled">
</div>
</form> 

Now, by default input id="5" will be disabled. But I also want to remove it. I am able to get it with JavaScript by loading in my header (although I can't guarantee the move to be smart)

<script>
$(document).ready(function(){
  $("[disabled=disabled]").parent().remove();
});
</script>

So far so good, the div element is removed. Yet, I want to put the element back and in the original position when the radio button corresponding to Female is clicked. I added in the header, just below the previous js script this

<script type='text/javascript' src='scripts/enable_elements.js'></script> 

which loads this function

// enable_elements.js

$(document).ready(function(){

    $('#4').click(function(){
    $( '#5' ).prop( "disabled", false );
    });

});

Yet the all thing doesn't work. I guess the problem could be the my ready(function)s are only loaded once at the beginning and then put to sleep? Should I structure my form differently?

  • 写回答

2条回答 默认 最新

  • dotn30471 2014-10-27 06:18
    关注

    You do not want to remove(), instead you want to hide().

    $(document).ready(function(){
        $("#5").hide();
    });
    

    Also you want to handle the click on #3:

    $('#3').click(function(){
        $( '#5' ).attr("disabled", "disabled").hide();
    });
    $('#4').click(function(){
        $( '#5' ).attr("disabled", "").show();
    });
    

    Note: I kept the "disabled" attribute, but really you don't need it since it will be hidden when unselectable...

    If you remove the #5, then it's lost and you cannot show it again. So clicking on Male, then Female, back on Male, and on Female again... would not work.

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(1条)

报告相同问题?

悬赏问题

  • ¥15 关于#hadoop#的问题
  • ¥15 (标签-Python|关键词-socket)
  • ¥15 keil里为什么main.c定义的函数在it.c调用不了
  • ¥50 切换TabTip键盘的输入法
  • ¥15 可否在不同线程中调用封装数据库操作的类
  • ¥15 微带串馈天线阵列每个阵元宽度计算
  • ¥15 keil的map文件中Image component sizes各项意思
  • ¥20 求个正点原子stm32f407开发版的贪吃蛇游戏
  • ¥15 划分vlan后,链路不通了?
  • ¥20 求各位懂行的人,注册表能不能看到usb使用得具体信息,干了什么,传输了什么数据