Javascript to click button - javascript

Below i have a html code
<td valign="top" id="UserManagebutton1"><input type="button" value="Add" class="inputbutton">
<input type="button" value="Delete" class="inputbutton">
<input type="button" value="Import" class="inputbutton">
<input type="button" value="Export" class="inputbutton">
<input type="button" value="Change Status" class="inputbutton">
<input type="button" value="Purge AD Users" class="inputbutton"></td>
I tried putting this into my console but it did not work. I am trying to click the Add Button.
Below is the code i used.
document.getElementById('Add').click();
Any idea why its not working? It works with others.

Since it seems that you do not have control over the page you are trying to manipulate, you will have to work with the HTML as it is. In this case, providing you do have control over the browser you are using (are you doing this from the console?), you can use document.querySelector: Documentation here.
So, in your specific case, you'd want to do
document.querySelector('[value="Add"]').click()
Or, to make things more specific, you could do
document.querySelector('#UserManagebutton1 input[value="Add"]').click()
Here is a fiddle with an example: http://jsfiddle.net/xonev/V6SQ2/

Use
<input type="button" id="Add" value="Add" class="inputbutton">
document.getElementById('Add').click();
Note you need id="Add" in order to get it using getElementById('Add')

You have no unique identifiers for your buttons. Make an ID that is the same as the value.
<td valign="top" id="UserManagebutton1">
<input type="button" id="Add" value="Add" class="inputbutton">
<input type="button" id="Delete" value="Delete" class="inputbutton">
<input type="button" id="Import" value="Import" class="inputbutton">
<input type="button" id="Export" value="Export" class="inputbutton">
<input type="button" id="Change" value="Change Status" class="inputbutton">
<input type="button" id="Purge" value="Purge AD Users" class="inputbutton">
</td>
Use this, then your code will work.

In your code you have set the value of the button to Add which simply means that the text that will appear on the button is Add. Value, as an attribute sets the text of that element.
If you want to access that element by id, you need to specify an id attribute for it, like this:
<input id="Add" class="inputbutton" type="button" value="Add">
And to access the button you could simply use the code that you have used in your post:
document.getElementById('Add').click();
Also, if you do not want to modify your current code, you could simply use another javascript selector to get that specific element, such as:
document.getElementsByClassName('inputbutton')[0].click();
Moreover, if you want to add click event listeners for the other elements, as you do for the Add button, you could do some Event Delegation which is great to manage performance:
// Bind the event listener to the top most element that contains your event targets
document.addEventListener('click', function(event){
// Get target of the event
var target = event.target || event.srcElement;
switch(target.value) {
case('Add'):
alert('Add button clicked!');
break;
...
// Add cases for the other buttons as well
}
});
Here is a simpler version that only listens for clicks on the Add button:
document.addEventListener('click', function(event){
var target = event.target || event.srcElement;
if (target.value == 'Add') {
alert('You clicked?');
}
});

If you are not using any JS libraries, try:
document.getElementsByName('Add')[0].click()
UPDATED - correction below
Since the buttons don't have name attributes (thanks #Rocket Hazmat) and since you cannot change the HTML, you can try this instead:
document.getElementsByTagName('input')[0].click();
// [0] for add button,
// [1] for Delete button,
// etc.

Related

JS Display a button when an element is Disabled

First time here ...
Im a beginner in JS .
I want to display an input only when another input has a disabled attribute:
<button type="button" id="Last"> Last </button>
<button type="button" id="Go" style="display:none"> Go </button>
after few click, and using jQuery, $("#Last").attr("disabled", "disabled"), I get (using the inspect tool) :
<button type="button" id="last" disabled="disabled"> Last </button>
I want to display this:
<button type="button" id="Go" style="display:block"> Go </button>
I tried this:
$( document ).ready(function() {
if($("#Last").prop('disabled', true)) {
$('#Go').show();
} else {
$('#Go').hide();
}
});
I doesn't work! Dont know where is the problem!
You should show the button when the button is clicked. See the commented code below.
// When button is clicked
$("#last").on("click", function() {
// Set button disabled to true
$(this).prop("disabled", true);
// Show the #go button
$("#go").show();
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<button type="button" id="last"> Last </button>
<button type="button" id="go" style="display:none"> Go </button>
I have changed to ids to all lowercase. That is a good coding convention.
as describe in the doc at this link http://api.jquery.com/prop/ the method prop(name, xxx) set the property name to the value xxx, o in your code the if statement is disabling the button last. You should use:if($("#Last").prop('disabled'))
$('#Go').show();
Be carefull that if you place this piece of code in $( document ).ready it only run once the page DOM is ready for JavaScript code to execute.

Apply a CSS rule for a specific button that belongs to a class

I have for example a web page that displays blog posts. Each blog posts has a 'comment' button and a 'like' button. When the user likes a post I want to apply a CSS style for that particular button. I have tried in many ways for example using "getElementsByClassName" to get the class of the button but it applies the rule for all the buttons. So if I have 5 blog posts all of them appear to be liked when I just like one of them. This is my JS code:
Template.post.events({
"click .like":function(event) {
var likeButton1=document.getElementsByClassName('like');
$(likeButton1).addClass('likeClick');
var nrLikes=parseInt(this.likes);
blogPosts.update(
this._id,{
$set:{"likes":nrLikes+1}
}
);
}
});
And this is my html code:
<input class="like" type="submit" name="like" value="Like"/>
Basically I need the instance of that particular clicked button, how do I do this? Thanks in advance!
document.getElementsByClassName returns a HTMLCollection. You can iterate over this collection and use array methods by doing
Array.prototype.forEach.call(HTMLCollection,callBackFunction)
Inside the callback function you can add an event listener to add the class on the element on click on it.
Below is a snippet which may be useful.
classList.add will add a new class to the existing element
var likeButton1 = document.getElementsByClassName('like');
Array.prototype.forEach.call(likeButton1, function(el) {
el.addEventListener('click', function() {
this.classList.add('likeClick')
})
});
.likeClick {
color: green
}
<input class="like" type="submit" name="like" value="Like" />
<input class="like" type="submit" name="like" value="Like" />
<input class="like" type="submit" name="like" value="Like" />
<input class="like" type="submit" name="like" value="Like" />
<input class="like" type="submit" name="like" value="Like" />
<input class="like" type="submit" name="like" value="Like" />
<input class="like" type="submit" name="like" value="Like" />
use this jQuery Code
$('.class_name').each(function () {
$(this).addClass('likeClick');
});
Instead of selecting all the elements with the class like, try targetng the specific element that received the click event (using the event object you're passing into your "click . like" handler). This assumes the event in this case represents an event object that has a target property, of course.
var likeButton1= event.target; // this will be the element that received the `click`
$(likeButton1).addClass('likeClick');
It sounds like you want to use a CSS psuedo class. That is how you can style a button that has been clicked or visited. This can all be done in your css file.
Example css file:
input .like {
(some css styling)
}
input .like:visited {
(different css styling)
}
You can also use link, hover, and active psuedo classes. Here's the reference:
https://www.w3schools.com/css/css_pseudo_classes.asp

How to change display value of the Submit button on page load using jquery

I am new to JQuery and need suggestions on following requirement.
I have a form with a submit button as below. Page accepts locale as an input parameter. Depending on the value of locale, on page load I am populating the labels of the input fields in respective language using jQuery.i18n.properties.js plug-in, but I could not update the display value of the button.
Please suggest solution or if there is another way to achieve this.
HTML code:
<input type="submit" data-inline="true" id="submit" value="Submit"/>
Have tried below jQuery options to update the button label:
$("#submit").val($.i18n.prop('submit'));
$("#submit").html($.i18n.prop('submit'));
$("#submit").prop('value',($.i18n.prop('submit')));
$("#submit").text($.i18n.prop('submit'));
None of them worked. But I see the value gets updated as below in Developer tools window, for this button.
<div class="ui-btn ui-input-btn ui-corner-all ui-shadow">
Submit
<input type="submit" id="submit" value="New Text">
</div>
Try $("#submit")[0].value = $.i18n.prop('submit');. Does that work for you?
(Even though it's a JS workaround, not a JQuery solution)
If your button is an input tag, use the jQuery val:
function changeBtnText() {
$("#submit").val("My new button text");
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input type="submit" id="submit" value="My button">
<button type="button" onclick="changeBtnText()">Change button text</button>
If your button is a button tag, use the jQuery text (or html):
function changeBtnText() {
$("#submit").text("My new button text");
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<button type="submit" id="submit">My button</button>
<button type="button" onclick="changeBtnText()">Change button text</button>
Note: I recommend giving your button an ID different from "submit" to avoid confusion.

Simulate click of javascript Button

How can i simulate a click of the button below? I tried using the javascript
$("#Save").click() but it didnt work. Does this have to do with it not working because there is no id but name?
<input class="button" type="submit" name="Save" value="Save" onclick="OnSubmit(this.form);">
What javascript command in my browser would i use to simulate the click of Save following something like i tried to use?
Much help appreciated! Im new to this
It appears your using jQuery with an id selector (# denotes an id), however the element doesn't have an id. Since the element does have a name attribute, an attribute selector can be used by jQuery. An appropriate selector would be:
$('input[name="Save"]').click(); //Assuming no other elements have name=Save
JS Fiddle: http://jsfiddle.net/pJD3R/
You could also change the markup to work with your existing selector by adding an id attribute:
<input id="Save" class="button" type="submit" name="Save" value="Save" onclick="OnSubmit(this.form);">
$("#Save").click() mean you target an element with the id save but you don't have any id on your input.
<input class="button" id="save" type="submit" name="Save" value="Save" onclick="OnSubmit(this.form);">
$('input[name=Save]').click(function(){
alert('Do Something');
});

Is it possible to use action="someFunction()" when a form is submitted?

From looking around on the web, I have not seen many examples of setting a function equal to a function. However, in the few forums I found, it appears that many say that this method is not widely supported.
To explain my question, I have a form I would like to implement this on:
<table border="0" cellpadding="2" cellspacing="5">
<th colspan="2" align="center">Check Out</th>
<form name="checkOut" method="post" onSubmit="return(validate(this))" action="checkOut()">
<tr><td>Territory Number</td><td><input type="text" name="numberOut" tabindex="1" maxlength="3" size="3" /></td>
</tr><tr><td>First Name of Publisher</td><td><input type="text" onKeyUp="showHint(this.value)" name="fName" tabindex="2" maxlength="15"/></td>
</tr><tr><td>Last Name of Publisher</td><td><input type="text" onKeyUp="showHint_l(this.value)" name="lName" tabindex="3" maxlength="15" /></td>
</tr><tr><td><input type ="checkbox" name="specialC" tabindex="4" value="Yes"/> Special Campaign</td>
</tr><tr><td><input type="button" onClick="clearForm()" value="Reset" /></td><td><input type="submit" value="Check Out" /></td>
</form>
<p>Suggestions: <span id="txtHint"></span></p>
</table>
More specifically, the checkOut() function will be using ajax to submit the form values to a php script that runs a few insert commands against a database (I want to use ajax to learn the technique as I'm fairly new to web-based languages. Therefore, I want to put off the use of jQuery for awhile). As of right now, I don't have an example of the function.
Naturally, that begs the question, could I simply put that function into the event handler: onSubmit = "checkOut()"? At the same time, I would leave action=""? I would assume that the entire function would execute the php script and do exactly what I want without having a separate action script.
Any feedback would be appreciated.
Use <input type="button" /> (or an anchor, or a button, or whatever) instead of <input type="submit" />. On the click event of the button, execute:
if(validate(document.getElementById("formId"))){
// post the form w/ AJAX
checkOut();
}
Keep in mind that any script-based solution should probably have a non-script option. In this case, it could be as easy as putting an <input type="submit" /> inside noscript tags.
Incidentally, your markup is invalid. A form can't appear as a direct child of a table.
You could make it the action="javascript:checkOut();" but it would almost certainly be better to put it in the onSubmit handler.
use this code is the best way to do that
<input type="submit" id="submit_button">
and javascript code like this
var submit = getElementById('submit_button');
submit.preventDefault();
submit.addEventListener('click', checkOut);
in first line we specific the button and next we prevent to do the default action and next we add a listener for when button clicked
I typically use:
<input type="button" value="Submit" onclick="myFunction();">
And then my function would use the native submit function at the bottom if everything checks out.:
if (isSuccess)
theForm.submit();
else
return false;

Categories