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 想问一下树莓派接上显示屏后出现如图所示画面,是什么问题导致的
  • ¥100 嵌入式系统基于PIC16F882和热敏电阻的数字温度计
  • ¥15 cmd cl 0x000007b
  • ¥20 BAPI_PR_CHANGE how to add account assignment information for service line
  • ¥500 火焰左右视图、视差(基于双目相机)
  • ¥100 set_link_state
  • ¥15 虚幻5 UE美术毛发渲染
  • ¥15 CVRP 图论 物流运输优化
  • ¥15 Tableau online 嵌入ppt失败
  • ¥100 支付宝网页转账系统不识别账号