简体   繁体   English

如何为动态创建的输入选择下拉选项时调用jquery函数?

[英]How can I call a jquery function on selecting a dropdown option for dynamically created inputs?

So this is what the page looks like currently: 所以这是页面当前的样子:

在此处输入图片说明

The first one is hardcoded in and then the rest are added/removed by the buttons. 第一个被硬编码,然后其余的通过按钮添加/删除。 The first one can also be added and removed from the buttons. 也可以从按钮中添加和删除第一个。 I want to call a jquery function when the dropdown is changed to change the type from textbox/radiobutton (and text)/checkbox (and text) etc. 我想在更改下拉列表以更改文本框/单选按钮(和文本)/复选框(和文本)等类型时调用jquery函数。

Currently it only works on the first Question/Answer and only works if it is the original and not dynamically created. 当前,它仅适用于第一个“问题/答案”,并且仅当它是原始的且未动态创建时才适用。 I'm not sure why that is. 我不确定为什么会这样。

Here is how the Q/A's are created and removed 这是创建和删除Q / A的方法

$("#addButton").click(function () {

    if (counter > max_fields) {
        alert("Only " + max_fields + " Questions allowed");
        return false;
    }

    var newTextBoxDiv = $(document.createElement('div'))
         .attr("id", 'TextBoxDiv' + counter);

    newTextBoxDiv.after().html('<label>Question #' + counter + ' : </label>' +
          '<input type="text" name="textbox' + counter +
          '" id="questionbox' + counter + '" value="" />' +
          ' <select id="choice'+ counter +'"><option>Type</option><option>Radio Button</option><option>Text Box</option><option>Check Box</option></select>' +
          '<button id = "remove' + counter + '">Remove</button>' +
          '<br/><label>Answer #' + counter + ' : </label>' +
          '<div id="Answers' + counter + '">' +
          'Option 1: <input type="text" id="answerbox' + counter +
          '1" name="answerbox' + counter + '" value="" />' +
          '<br/>Option 2: <input type="text" id="answerbox' + counter +
          '2" name="answerbox' + counter + '" value="" />' +
          '<br/>Option 3: <input type="text" id="answerbox' + counter +
          '3" name="answerbox' + counter + '" value="" />' +
          '<br/>Option 4: <input type="text" id="answerbox' + counter +
          '4" name="answerbox' + counter + '" value="" /></div>');

    newTextBoxDiv.appendTo("#TextBoxesGroup");
    counter++;
});

$("#removeButton").click(function () {
    if (counter == 1) {
        alert("No more textbox to remove");
        return false;
    }
    counter--;
    $("#TextBoxDiv" + counter).remove();
});

This is how I tried to get it to change types 这就是我试图使其更改类型的方式

$('#choice1').change(function () {
    var selected_item = $(this).val()
    var searchEles = document.getElementById("Answers1").children;
    alert(searchEles.length);
    for(var i = 0; i < searchEles.length; i++) {
        $('#answerbox1' + i).attr('type', selected_item);
        //alert(searchEles.length);
    }

});

The web page code is as follows 网页代码如下

<input type='button' value='Add Question' id='addButton'/>
<input type='button' value='Remove Question' id='removeButton'/>
<div id='TextBoxesGroup'>
    <div id="TextBoxDiv1">
        <label>Question #1 : </label>
        <input type='text' id='questionbox1'/> 
        <select id="choice1" onchange="$('#choice').val('id');"> //this on change was added and currently does nothing it seems.
            <option value="">Type</option>
            <option value="radio">Radio Button</option>
            <option value="text">Text Box</option>
            <option value="checkbox">Check Box</option>
        </select>
        <button id="remove1">Remove</button>
        <br/><label>Answer #1 : </label>
        <div id="Answers1">
            Option 1: <input type="text" id='answerbox11' name='answerbox1'  value="" />
            <br/>Option 2: <input type="text" id='answerbox12' name='answerbox1'  value="" />
            <br/>Option 3: <input type="text" id='answerbox13' name='answerbox1'  value="" />
            <br/>Option 4: <input type="text" id='answerbox14' name='answerbox1'  value="" />
        </div>
    </div>
</div>

I tried to do something like onchange and then get the ID and go from there but that didn't work. 我试图做类似onchange的事情,然后获取ID并从那里去,但这没有用。 I know it doesn't match the back end jquery name. 我知道它与后端jquery名称不匹配。

TL;DR TL; DR

  1. I don't know how to dynamically write the jQuery function to work for all of them. 我不知道如何动态地编写jQuery函数来为所有这些工作。
  2. I don't know why even if I hardcode it to #choice1 it will work when its first created but not if i remove and add it even though it has the same exact values. 我不知道为什么即使我将其硬编码到#choice1时,它在第一次创建时仍可以工作,但是即使我具有相同的确切值,也不能删除并添加它,为什么不行。 I think it might MAYBE have to do with for loop, because the alert doesn't even trigger the second time around. 我认为可能与for循环有关,因为警报甚至不会在第二次触发。

You could try 你可以试试

$(document).on("change", ".selector", function(){
  //do something

});

//Edit //编辑

Add to the select element class for example select-option and a tag that will hold the select's counter 添加到select元素类中,例如select-option和一个将保留select计数器的标记

//JS    
...'<select id="choice'+counter+'" class="select-option" number="'+counter+'">'...

and then your on change function would look something like 然后您的on change函数看起来像

$(document).on("change", ".select-option", function(){
  //do something
  var selected_type = $(this).attr('value');
  var ans_number = $(this).attr('number');
  $("#answerbox"+ans_number).children('input').attr('type', selected_type);
});

I hope this will help :) 我希望这个能帮上忙 :)

对于动态添加的元素,请使用

$(selector).on("change", callback)

If element is dynamic then Jquery will not bind directly as 如果element是动态的,那么Jquery将不会直接绑定为

$('#choice1').change(function (){});

But for that you need to call same function with some static element. 但是为此,您需要使用一些静态元素来调用同一函数。 For Ex: 例如:

 $(".listingDiv").find('#choice1').change(function (){});

or 要么

$(document).find('#choice1').change(function (){});

and it will work. 它会工作。 try it. 试试吧。

When elements will be aded dynamically, best practice is to delegate the handler(s). 当元素将被动态添加时,最佳实践是委派处理程序。 Put your handler on the containing div or window/document . 将处理程序放在包含div或window / document上。

  • First 第一

     <select id="choice1" onchange="$('#choice').val('id');"> //this on change was added and currently does nothing it seems. 

    This is one reason your never be called. 这是您永远不会被召唤的原因之一。 If you bind an event listener to an element, you should not write the actual JS code inside the element. 如果将事件侦听器绑定到元素,则不应在元素内部编写实际的JS代码。

  • Second 第二

    Bind your listener like this: 像这样绑定您的听众:

 $('#choice1').on("change", function () { var selected_item = $(this).val() var searchEles = document.getElementById("Answers1").children; alert(searchEles.length); for(var i = 0; i < searchEles.length; i++) { $('#answerbox1' + i).attr('type', selected_item); //alert(searchEles.length); } }); 

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 如何使用 PHP 或 Jquery 从动态创建的下拉列表中获取所选选项的 ID? - how I can get the ID of the selected option from a dynamically created dropdown using PHP, or Jquery? jQuery在动态创建的下拉菜单上调用onchange函数 - Jquery Call onchange function on dynamically created dropdown 如何通过更改下拉菜单选项调用其他功能 - how can i call different function by change dropdown menu option jQuery自动完成功能,可为ajax调用动态创建输入 - jQuery autocomplete for dynamically created inputs for ajax call 如何在动态创建的元素上调用jQuery函数 - How to call a jQuery function on dynamically created element 填充使用 jquery 动态生成的输入,同时在 select 框中选择一个选项 - Fill inputs that are generated dynamically with jquery while selecting an option in the select box jQuery .on(&#39;change&#39;, function() {} 不会触发动态创建的输入 - jQuery .on('change', function() {} not triggering for dynamically created inputs 如何跟踪动态创建的输入值? - How can I keep track of the value of inputs that are dynamically created? jQuery-使用“ nth”动态选择输入 - JQuery - dynamically selecting inputs with “nth” 如何在动态创建的选择标记中添加一个空选项? - How can I add an empty option in a select tag created dynamically?
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM