2014-01-22 21 views
0
<div id="sandbox"> 
<p> 
    <label> Answer Type</label> 
    <select name="ans_type[]"> 
     <option value="Image">Image</option> 
     <option value="Text">Text</option> 
    </select> 
</p> 
<p class="text"> 
    <label> Enter Answer</label> 
    <textarea rows="5" cols="50" name="ans_text[]"></textarea> 
</p> 
<p class="image"> 
    <label> Upload Image</label> <br/> 
    <input type="file" name="ans_image[]" class="btn"/> 
</p> 
<p> 
    <label> Is Correct Answer</label> 
    <input type="checkbox" name="isCorrectAnswer[]"/> 
</p> 

上改變下拉列表中沒有觸發

JS

$('#addButton').click(function() { 
     var newHTML = ""; 
     newHTML += '<p><label> Answer Type</label><select name="ans_type[]"><option value="Image">Image</option><option value="Text">Text</option></select></p><p><label> Enter Answer</label><textarea rows="5" cols="50" name="ans_text[]"></textarea></p><p><label> Upload Image</label> <br/><input type="file" name="ans_image[]" class="btn"/></p>'; 
     $('#sandbox').html($('#sandbox').html() + newHTML); 
    }); 
    $("input[name*='ans_type']").change(function() { 
     alert("asd"); 
     var answer = $(this).val(); 
     if (answer == "Image") { 
      $(".text").hide(); 
      $(".image").show(); 
     } else { 
      $(".text").show(); 
      $(".image").hide(); 
     } 
    }); 

當我選擇下拉ans_type改變功能的列表不會觸發。這個問題應該放在input [name * ='ans_type'] < - 因爲當用戶點擊Add按鈕時,會複製輸入,所以我應該如何改變這個以使所有ans_type []下拉列表中的效果可用。

回答

0

這應該是$("select[name*='ans_type']")而不是$("input[name*='ans_type']"),因爲你的目標selectinput元素

您還可以使用事件代表團動態添加元素:

$(document).on("change","select[name*='ans_type']", function(){ 
    alert("asd"); 
    var text = $(this).closest('#sandbox').find('.text'), 
     image = $(this).closest('#sandbox').find('.image'), 
     answer = $(this).val(); 
    if (answer == "Image") { 
     text.hide(); 
     image.show(); 
    } else { 
     text.show(); 
     image.hide(); 
    } 
}) 
+0

謝謝,我代碼現在如果一個文本更改爲所有其他答案將更改爲文本以及反之亦然,我該如何修改s o當我選擇這個特定的答案來格式化文本時,只有當前的一個會改變其他的東西。 – user236501

+0

@ user236501看到我更新的答案,您需要替換'$(「。text」)。hide();','$(「。text」)。show();'以確保您的目標文字正確。對圖像也做同樣的事情。 – Felix

+0

Yaya我明白了,我的問題是當我添加ans_type select時,輸入文本字段將會重複一次,因爲您可以看到我保存爲[]的名稱。我將

user236501

0

嘗試

$("select[name*='ans_type']")