如何使用JavaScript

时间:2015-12-03 04:55:59

标签: javascript attributes

我是js编程的新手,我在这里有项目,我需要在点击链接时更改默认的name属性值。这是我目前的表格:

<form id="searchform" action="" method="GET">
            <input id="intextbox" maxlength="150" size="20" value="" name="q" type="text" placeholder="Insert your keyword here..">
            <input id="wpbdmsearchsubmit" class="submit wpbdp-button wpbdp-submit" value="Search" type="submit">
            <div class="search-filter">
                Search By: <a id="FilterByContinent">Continent</a> | <a id="FilterByCountry">Country</a> | <a id="FilterByFlag">Flag</a>
            </div>
        </form>

======================

如您所见,输入#intextbox的默认名称值是 q ,我想在点击Continent链接时将其更改为 listingfields [1]

所以来自:

<input id="intextbox" maxlength="150" size="20" value="" name="q" type="text" placeholder="Insert your keyword here..">

为:

<input id="intextbox" maxlength="150" size="20" value="" name="listingfields[1]" type="text" placeholder="Insert your keyword here..">

如何使用JavaScript执行此操作?谢谢你将来的帮助。干杯!

2 个答案:

答案 0 :(得分:1)

您的解决方案就在这里:

<form id="searchform" action="" method="GET">
    <input id="intextbox" maxlength="150" size="20" value="" name="q" type="text" placeholder="Insert your keyword here..">
    <input id="wpbdmsearchsubmit" class="submit wpbdp-button wpbdp-submit" value="Search" type="submit">
    <div class="search-filter">
        Search By: <a id="FilterByContinent" onclick="changename();" >Continent</a> | <a id="FilterByCountry">Country</a> | <a id="FilterByFlag">Flag</a>
    </div>
</form>

<script>
function changename(){
    document.getElementById('intextbox').name = "listingfields[1]";
}
</script>

答案 1 :(得分:1)

检查出来:

//getting the name attribute before:
var currentName = document.getElementById("intextbox").name;
document.getElementById("intentBoxName").innerHTML = currentName;

//Now for changing the name attribute of input,
//first add an Event Listener to the continent link:

var continentLink = document.getElementById("FilterByContinent");
continentLink.addEventListener("click", function() {
  document.getElementById("intextbox").name = "listingfields[1]";

  //Just for showing the change in the name attribute:
  var newName = document.getElementById("intextbox").name
  document.getElementById("intentBoxName").innerHTML = newName;
});
<form id="searchform" action="" method="GET">
  <input id="intextbox" maxlength="150" size="20" value="" name="q" type="text" placeholder="Insert your keyword here..">
  <input id="wpbdmsearchsubmit" class="submit wpbdp-button wpbdp-submit" value="Search" type="submit">
  <div class="search-filter">
    Search By: <a id="FilterByContinent">Continent</a> | <a id="FilterByCountry">Country</a> | <a id="FilterByFlag">Flag</a>
  </div>
</form>


<br/>
<br/>

<h5> Name Attribute: </h5>
<div id="intentBoxName"></div>

如果您刚刚使用Google搜索“使用javascript更改名称属性”,您可以轻松找到答案。你应该花一些时间在google上查看,然后再将其作为一个问题发布。我希望上面的代码片段符合你的期望。