Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Call JavaScript/AJAX with a button without onClick function by his input name. Is it possible?

Got the next html code:

<form name="frm">
   <textarea class="textarea" name="textarea" id="textarea">
     <?php
        foreach ($textarea as $textareashow){
          echo $textareashow."\r\n";
        }?>
   </textarea><br><br>
   <input type="button" name="callbutton" value="Push button" id="execbutton" />
</form>

And the next JavaScript code:

$(document).ready(function () {
  $('#callbutton').click(function () {
     alert("HELLO!!!");
  });
});

What I want is to call the JavaScript function from his button input name. Is it possible? and from his input id? Thank you very much.

like image 201
user3321425 Avatar asked Apr 17 '15 08:04

user3321425


2 Answers

Try this:

$(document).ready(function () {
    $('#execbutton').click(function () {
       alert("HELLO!!!");
   });
});

Will work.

Explanation: # is used to select the element by id and . is used to select an element by classname. you are selecting element by name so you need to use the $("input[name=callbutton]"). If you are selecting any element by its property or attribute then you need to use it in [] brackets. [property_name=property_name_value] like this.

like image 115
Code Lღver Avatar answered Oct 08 '22 05:10

Code Lღver


Of course it's possible. I've posted a jsfiddle below

You can use following jQuery selectors : #id and input[name=something] ( you don't need to use both of them )

To add a click event on a button ( in your case ) you can use .click(function(){})

So :

$(function(){
     $("#your_btn_id").click(function(){   // using selector by id
          // do something
     });

     $('input[name="your_btn_name"]').click(function(){  // using selector by name
         // do something
     });   
})

You can also combine selectors :

$(function(){
     $('#your_btn_id, input[name="your_btn_name"]').click(function(){   
          // do something
     });


     // or


    $("#your_btn_id").add('input[name="your_btn_name"]').click(function(){   
          // do something
     });
})

Fiddle

like image 25
Cosmin Avatar answered Oct 08 '22 05:10

Cosmin