2013-05-08 31 views
0

我有一個隱藏的輸入字段的Web表單如下刪除文本字符串:如何添加和使用jQuery

​​3210

我想基於使用jQuery一定條件添加和刪除「,location」如下:

$('input[name="locationstatus"]:radio').on("change", function() { 
    if ($('input[name="locationstatus"]:radio:checked').val() == 'Yes') { 
     /* need syntax to append text ',location' to #requiredFields string */ 
    } 
    else { 
     /* need syntax to remove text ',location' from #requiredFields string */ 
    } 
}); 

感謝

回答

3

使用jQuery的.val()更新的requiredFields

0123的值
$('input[name="locationstatus"]:radio').on("change", function() { 
    if ($('input[name="locationstatus"]:radio:checked').val() == 'Yes') { 
     $('#requiredFields').val($('#requiredFields').val() + ',location'); 
    } 
    else { 
     $('#requiredFields').val($('#requiredFields').val().replace(',location','')); 
    } 
}); 
+0

這看起來簡化了@Sharlike。我現在要測試併發回。 – 2013-05-08 18:20:54

+0

完美@Sharlike - 正是我所需要的。只要SO允許我接受這個答案,我就會這樣做 – 2013-05-08 18:24:50

+0

@ H.Ferrence很高興這是你所需要的 – Sharlike 2013-05-08 18:31:48

0

而不是試圖追加/刪除字符串的一部分,它可能會更容易和更快只需更換整個字符串,假設沒有其他的字符串,在這種情況下,我可以提供更健壯的解決方

$('input[name="locationstatus"]:radio').on("change", function() { 
    if ($('input[name="locationstatus"]:radio:checked').val() == 'Yes') { 
     /* need syntax to append ',location' to #requiredFields */ 
     $('#requiredFields').val('firstname,lastname,email,phone,location'); 
    } 
    else { 
     /* need syntax to remove ',location' from #requiredFields */ 
     $('#requiredFields').val('firstname,lastname,email,phone'); 
    } 
}); 
0

如果你想要的位置追加到最後,你可以使用.val()方法。它也可以設置元素的值。

$('input[name="locationstatus"]:radio').on("change", function() { 
    if ($('input[name="locationstatus"]:radio:checked').val() == 'Yes') { 
     var prev = $("#requiredFields").val(); 
     $("#requiredFields").val(prev + ',location'); 
    } 
    else { 
    var newText = $("#requiredFields").val().replace(',location', ''); 
    $("#requiredFields").val(newText); 
    } 
});