开发者

Javascript: how to change form fields value with single click

开发者 https://www.devze.com 2022-12-17 18:23 出处:网络
I\'m trying to set t开发者_StackOverflow社区he value of three different input text fields with an onclick function.

I'm trying to set t开发者_StackOverflow社区he value of three different input text fields with an onclick function.

I have an image that has this code...

<img src="images/delete_row.png" width="25" onClick="clearRow(0);" />

And I have three input text fields that all have the id of "0".

When I click my image I want to set the value of all three fields to empty.

Can someone please help me write a function that can do this?

Thanks!


First, you need your id values to be different. You should never have the same ID twice on the same page. So lets use this as the example HTML:

<input type="text" id="name_0"  name="name" />
<input type="text" id="phone_0" name="phone" />
<input type="text" id="email_0" name="email" />

You could use this JavaScript function:

<script type='text/javascript'>
  function clearRow(id){
     var name  = document.getElementById('name_' + id),
         phone = document.getElementById('phone_' + id),
         email = document.getElementById('email_' + id);

     // Clear values
     name.value = phone.value = email.value = "";
  }
</script>

And your img tag would remain unchanged:

<img src="images/delete_row.png" width="25" onClick="clearRow(0);" />


I have three input text fields that all have the id of "0".

This is entirely wrong. In a document you can't have element with the same id. Either use a name or a classname for these textfields and make their ids different.

<script type="text/javascript">
    function Change()
    {
        var elems = document.getElementsByName ( "myfields");
        for ( var i = 0;i < elems.length; i++)
        {
            elems[i].value = "";
        }
    }
</script>
<input name="myfields" type="text" id="txt1" />
<input name="myfields" type="text" id="txt2" />
<input name="myfields" type="text" id="txt3" />
<img onclick="Change();" alt="test" src="yourimagpath" />


<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.3.2/jquery.min.js"></script>

<script>
$(document).ready(function() {
  $('#pic').click(function() {
    alert('Clicked on pic - resetting fields')
    $('.field').val('')
  })
}
</script>

<img id="pic" src="image.png">
<input class="field" value="1">
<input class="field" value="2">
<input class="field" value="4">
<input class="field" value="5">
<input class="field" value="6">
<input class="field" value="7">
<input class="field" value="8">
<input class="field" value="9">
<input class="field" value="10">
0

精彩评论

暂无评论...
验证码 换一张
取 消