簡體   English   中英

使用JavaScript在HTML文本框之間切換HTML ID屬性值

[英]Switch HTML ID Attribute Value Between HTML Text-Boxes Using JavaScript

我的HTML表單中有很多HTML文本框(超過2個)。 第一次加載HTML頁面時,ID屬性為空。 但是,當用戶單擊文本框時,ID應該是“活動的”。 其他人應該是空的。 當用戶單擊另一個時,前一個文本框的ID應該為空。 新的文本框的ID應該為“活動”。

<input type="text" name="test" id="active">
<input type="text" name="test" id="">
<input type="text" name="test" id="">
<input type="text" name="test" id="">
<input type="text" name="test" id="">
<input type="text" name="test" id="">

如何使用JavaScript執行此操作? 有人可以幫我解決這個問題嗎?

感謝和問候,Chiranthaka。

您可以使用.focus()來檢測文本框上的焦點事件,以及removeAttr().attr()來將id設置為焦點元素:

$("[name='test']").focus(function() {
  $('#active').removeAttr('id');
  $(this).attr('id','active');
});

工作演示

您應該使用class屬性而不是id屬性。 因此,您可以執行以下操作:

var inputs = $('input[type="text"]');
inputs.click(function(){
    inputs.removeClass(active);
    $(this).addClass('active');
});

試試這個,這是一個純JavaScript解決方案。

<html>
<head>
<script>
function changeIds(selectedEle)
{
    var elements = document.getElementsByName("test");
    for(var index = 0 ; index < elements.length ; index++ )
    {
        elements[index].id="";
    }
    selectedEle.id="active";
}


</script>
<body>
<form id="myForm" >
    <input type="text" onclick="changeIds(this)" name="test" id="active">
    <input type="text" onclick="changeIds(this)" name="test" id="">
    <input type="text" onclick="changeIds(this)" name="test" id="">
    <input type="text" onclick="changeIds(this)" name="test" id="">
    <input type="text" onclick="changeIds(this)" name="test" id="">
    <input type="text" onclick="changeIds(this)" name="test" id="">
</form>
</body>
</html>

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM