How can I select a button based on its value and click on it (in Javascript)?
I already found it in JQuery:
$('input [type = button] [value = my task]');
My HTML Code for the Button is :
<button type="submit" value="My Task" id="button5b9f66b97cf47" class="green ">
<div class="button-container addHoverClick">
<div class="button-background">
<div class="buttonStart">
<div class="buttonEnd">
<div class="buttonMiddle"></div>
</div>
</div>
</div>
<div class="button-content">Lancer le pillage</div>
</div>
<script type="text/javascript" id="button5b9f66b97cf47_script">
jQuery(function() {
jQuery('button#button5b9f66b97cf47').click(function () {
jQuery(window).trigger('buttonClicked', [this, {"type":"submit","value":"My Task","name":"","id":"button5b9f66b97cf47","class":"green ","title":"","confirm":"","onclick":""}]);
});
});
</script>
What is the equivalent in JS and how may i click on it
(probably like this: buttonSelected.click(); ) .
And how do i run the javascript of the button clicked ?
Use querySelector to select it. Then click()
Your HTML has a button and not an input element so I changed the selector to match the HTML.
let button = document.querySelector('button[value="my task"]');
button.click();
<button type="submit" value="my task" id="button5b9f54e9ec4ad" class="green " onclick="alert('clicked')">
<div class="button-container addHoverClick">
<div class="button-background">
<div class="buttonStart">
<div class="buttonEnd">
<div class="buttonMiddle"></div>
</div>
</div>
</div>
<div class="button-content">Launch</div>
</div>
</button>
Otherwise, use this selector:
document.querySelector('input[type="button"][value="my task"]')
Note that if you have multiple buttons with the same value you'll need to use querySelectorAll and you'll get a list of all the buttons.
Then you can loop over them and click() them all.
Edit - new snippet after question edit
jQuery(function() {
jQuery('button#button5b9f66b97cf47').click(function() {alert('success')});
document.querySelector('button[value="My Task"]').click();
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<button type="submit" value="My Task" id="button5b9f66b97cf47" class="green ">
<div class="button-container addHoverClick">
<div class="button-background">
<div class="buttonStart">
<div class="buttonEnd">
<div class="buttonMiddle"></div>
</div>
</div>
</div>
<div class="button-content">Lancer le pillage</div>
</div>
you can try:
var elements = document.querySelectorAll("input[type = button][value=something]");
note that querySelectorAll returns array so to get the element you should use indexing to index the first element of the returned array and then to click:
elements[0].click()
and to add a event listener u can do:
elements[0].addEventListener('click', function(event){
event.preventDefault()
//do anything after button is clicked
})
and don't forget to add onclick attribute to your button element in html to call the equivalent function in your javascript code with event object
I am not recommended this way because of excess your coding but as you mentioned, below are the equivalent way.
$(document).ready(function() {
var selectedbuttonValue = "2"; //change value here to find that button
var buttonList = document.getElementsByClassName("btn")
for (i = 0; i < buttonList.length; i++) {
var currentButtonValue = buttonList[i];
if (selectedbuttonValue == currentButtonValue.value) {
currentButtonValue.click();
}
}
});
function callMe(valuee) {
alert(valuee);
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.2.3/jquery.min.js"></script>
<input type="button" class="btn" value="1" onclick="callMe(1)" />
<input type="button" class="btn" value="2" onclick="callMe(2)" />
<input type="button" class="btn" value="3" onclick="callMe(3)" />
Using JavaScripts querySelector in similiar manner works in this case
document.querySelector('input[type="button"][value="my task" i]')
EDIT
You might save your selection in variable and attach eventListener to it. This would work as you desire.
Notice event.preventDefault() -function, if this would be part of form it would example prevent default from send action and you should trigger sending form manually. event-variable itselfs contains object about your click-event
var button = document.querySelector('input[type="button"][value="my task" i]')
button.addEventListener('click', function(event){
event.preventDefault() // Example if you want to prevent button default behaviour
// RUN YOUR CODE =>
console.log(123)
})
Related
First of all I'm adding a button via js:
let newTextArea = "<div class='row mt-4'><div class='col'><button type='button' class='btn btn-light rimuovi' onclick='removeIt()'>Rimuovi</button></div</div>";
Once on the page, I might want to remove it so I'm calling that function on a click:
function removeIt(e) {
e.closest(".row").remove();
}
but I'm getting
Cannot read properties of undefined (reading 'closest') at removeIt
You just forgot to pass your element (e) in the paramters in your JS fonction on the HTML.
So, try with :
onclick = 'removeIt(this)';
Working example:
function removeIt(e) {
e.closest(".row").remove();
}
<div class="row">
<button onclick='removeIt(this)'>Rimuovi</button>
</div>
Hope this helps you.
As others mentioned, you forgot to pass "this" as a parameter to your removeIt() method. The "this" keywords refers to, in this case, the element in which the click listener is used (your button). With the "this" keyword set as a parameter, JS can now look for a "closest" element with the class "row". It starts from the button and goes up the dom-tree until it finds an element with a className "row" or until it reaches the root.
Working example:
<!DOCTYPE html>
<html>
<body>
<div class="row mt-4">
<div class="col">
<button
type="button"
class="btn btn-light rimuovi"
onclick="removeIt(this)"
>
Rimuovi
</button>
</div>
</div>
<script>
function removeIt(element) {
closest = element.closest('.row');
closest.remove();
}
</script>
</body>
</html>
The main issue is because you aren't providing the e argument when you call the removeIt() function in the onclick attribute.
However you should note that using an inline onclick attribute is not good practice. A better way to achieve what you need is to attach an unobtrusive delegated event handler which accepts the Event object as an argument. You can then use that Event to retrieve the Element object which triggered the handler. Something like this:
const rowTemplate = document.querySelector('#row-template');
const container = document.querySelector('.container');
const addBtn = document.querySelector('.add');
addBtn.addEventListener('click', () => {
container.innerHTML += rowTemplate.innerHTML;
});
container.addEventListener('click', e => {
if (e.target.matches('.rimuovi'))
e.target.closest('.row').remove();
});
<button class="add">Add</button>
<div class="container"></div>
<template id="row-template">
<div class="row mt-4">
<div class="col">
<button type="button" class="btn btn-light rimuovi">Rimuovi</button>
</div>
</div>
</template>
I'm trying to do something like a social network, but I'm having problems with jquery, I want, by clicking the comment button, the user is taken to the comment field, but I'm not able to use $(this).
When the user click here
The code:
<button type="button" class="btn btn-default abreComentarios" >
<span class="fa fa-comments-o"></span>
</button>
The field:
The code:
<div class="comentar">
<textarea class="txtComentario form-control caixaComentario" placeholder="Seu comentário" onkeypress="comentarEnter()"></textarea>
</div>
My jquery:
$('body').on('click', '.abreComentarios', function() {
//console.log('entrou');
$(this).next('.caixaComentario').focus();
});
Remember, I'm using a foreach, so I have to use $(this)
Your next() isn't .caixaComentario but .comentar,
So use the next() but then you'll have to use find() (or children()) to focus the textarea
$('.abreComentarios').on('click', function() {
//console.log('entrou');
$(this).next('.comentar').find('.caixaComentario').focus();
})
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<button type="button" class="btn btn-default abreComentarios">click</button>
<div class="comentar">
<textarea class="txtComentario form-control caixaComentario" placeholder="Seu comentário"></textarea>
</div>
Solved, i just did it:
1- Added a data-id with the id of the post in the button
<button type="button" class="btn btn-default abreComentarios" data-id="'.$post->id.'"><span class="fa fa-comments-o"></span></button>
2- Added the same id in the end of the name of class "caixaComentario"
<div class="comentar">
<textarea class="form-control caixaComentario'.$post->id.'" placeholder="Seu comentário" onkeypress="comentarEnter()"></textarea>
</div>
3- Call without $(this) on jQuery
$('body').on('click', '.abreComentarios', function() {
var id = $(this).data("id");
$('.caixaComentario'+id).focus();
});
and Worked :D
$(this) will be your <button>, but calling .next(".caixaComentario") will look for a sibling element to the button. If your <button> and <div class="comentar"> are siblings, the .next(".caixaComentario") will not match any elements as they aren't siblings. The would be a niece/nephew.
Try changing .next(".caixaComentario") to .next("div .caixaComentario")
In meteor, I have created a cards dynamically after submitting the form. and the dynamic card contains the show and hide buttons. When I click on show option button the hidden part is showing for all the cards instead of that particular card. the problem is the card is creating dynamically so I thought that is problem .. how to make the functionality to work separately to the each card.
Here I am attaching the code:
<div id="newActionCard">
{{#each newaction}}
<div class="workflowcard">
<div class="module-card">
<div class="res-border"></div>
<div class="card-img"></div>
<div class="res-content">
<div class=" assigned-team">{{team}}</div>
<div class=" newaction-name">{{action_title}}</div><hr>
<div class="description">{{description}}</div>
<div class=" due-on">Due on:{{d_date}}</div><hr>
<div class="subcontent">
{{> actioncardsubcontent}}
</div>
<div class="reqext">
{{> requestextensioncard}}
</div>
</div>
<div class="due">
Due on:
<div>
<span class="day-stamp">THU</span><br>
<div class="date-stamp">26</div>
<div class="month-stamp">AUG
</div>
</div>
</div>
</div>
<div class="btn-box newaction">
<button type="button" class="cancelsub" >New Action</button>
<button type="submit" class="createbtnsub" >Show Options</button>
</div>
<div class="btn-box showoption">
<button type="button" class="hideoption" style="display:none">Hide Options</button>
</div>
{{/each}}
</div>
In JS I have written the hide and show functionalities in the events..now how to stop functionality to all cards at a time.
Here is my JS:
Template.workflow.events({
"click .createbtnsub" : function() {
$( ".subcontent" ).show();
$('.createbtnsub').hide();
$('.cancelsub').hide();
$('.hideoption').show();
$('.requestextension').show();
},
"click .hideoption": function(){
$('.subcontent').hide();
},
"click .hideoption": function(){
$(".subcontent").hide();
$('.cancelsub').show();
$('.createbtnsub').show();
$('.requestextension').hide();
$('.hideoption').hide();
$('.reqext').hide();
},
"click #createActionBtn": function(){
$('#createAction').hide();
$('.editw').show();
$('.hidew').show();
},
});
Template.actioncardsubcontent.rendered = function(){
this.$(".subcontent").hide();
};
Template.requestextensioncard.rendered = function(){
this.$(".reqext").hide();
};
Template.workflow.helpers({
getWorkflow: function(){
return Workflow.find();
},
user: function(){
return Meteor.users.find({});
},
getNewaction: function(){
return Newaction.find();
},
});
Please see the following and adjust the selectors as needed:
"click .showoption": function(event){
$(event.currentTarget).next('button').show();
}
This will work for selecting sibling elements, however as a tip I would recommend rewriting your template.helper that returns the cards data from the database into something more specific.
Something like dynamic classes based on index or id so your class/id names would return as follows .showoption-12kjddfse4 . Then you can just get the attribute of the current target and apply it to your js selector.
Also as kind of an explination to why all buttons were showing, is you were using the class selector, which is meant for grabbing groups of elements/nodes. This is also another reason to created more specific classnames/ids to your use case.
So in your class name you could do something like
<button class="showoption" id="{{_id}}">button</button>
<button id="hiddenoption-{{_id}}" class="hiddenoption">button</button>
Then selecting your elements would be easier as follows:
'click .showoption'(event) => {
let id = event.currentTarget.getAttribute(id);
document.getElementById('hiddenoption-'+id).style.display = 'block';
}
all. I have html layout like this:
<div class="row" id="1">
/*Other code has nothing to do with <div class="form-group col-lg-1">*/
<div class="form-group col-lg-1">
<input type="button" class="btn btn-default" onclick="updateLine()" value="Update">
</div>
</div>
I want to obtain the div's ID, in this case, which is 1.
This is what I did.
function updateLine() {
alert(this.parent().parent().attr("id"));
}
However, it failed, then I check
alert(this);
it returns to me the window object.
So the question is , how could I get the id's value, which is 1.
Thanks.
You need to pass this to the function as follows
<input type="button" class="btn btn-default" onclick="updateLine(this)" value="Update">
function updateLine(obj) {
alert(obj);
$(obj).closest('.row').attr('id'); // will return the id, note that numeric values like 1 are invalid
}
You do not need to pass this to the function. In an event handler this is the element clicked. However, to use .parent() etc on it you need the jQuery object for that element which is $(this)
Also, I would strongly recomment using .closest instead of .parent().parent(). Something like
$(this).closest('div.row').attr('id')
Way less likely to break when you make small layout changes...
The comments about using jQuery events instead of inline javascript are also good advice.
Example:
<div class="row" id="1">
/*Other code has nothing to do with <div class="form-group col-lg-1">*/
<div class="form-group col-lg-1">
<input type="button" class="btn btn-default" value="Update">
</div>
</div>
<script type="text/javascript">
$(function(){
function updateLine(event){
alert( $(this).closest('.row').attr('id') );
}
// If you have other buttons add a class like 'btn-update' and use that instead
$('body').on('click', '.btn-default', updateLine);
});
</script>
If you want to do inline event handlers, you need to pass this:
onclick="updateLine(this)"
then in js:
function updateLine(obj) {
alert($(obj).closest('.row').attr("id"));
}
However, I'd recommend removing the inline handler if possible and using jQuery to do the binding:
$('button').click(function() {
alert($(this).closest('.row').attr("id"));
});
What you are trying do is very bad practice. It will never work.
Firs, you should not use inline javascript.
Second, you should use real jQuery code.
Below you can see a working example.
<div class="row" id="1">
<div class="form-group col-lg-1">
<input type="button" class="btn btn-default" value="Update" id="someID" />
</div>
</div>
And your jQuery code should be like:
$(function () {
$('#someID').click(function () {
alert($(this).parents('div:eq(1)').prop('id'));
});
});
Here is a working example: http://jsfiddle.net/avramcosmin/Z9snq/
A bit late but what worked for me:
$(document).on('click', '.id', function(event) {
const elem = $(this);
})
I have the following code
<div class="framepage">
<header>
<script type="text/javascript">
function getBaseUrl() {
return "#Url.Content("~/paging")";
}
function LocationSearch(baseUrl) {
window.location = getBaseUrl() + "/LocationSearch?searchstring=" + (document.getElementById('vestigingen').value);
}
</script>
</div>
</div>
</div>
</header>
<section id="maintest">
<ul id="menu">
<li>
<form class="navbar-search">
<div class="icon-search icon-white"></div>
<input type="text" class="search-query span3" id="vestigingen">
</form>
<input type="button" class="buttonzz" value="zoeken" onclick="LocationSearch()"/>
</li>
<li>Lijst</li>
<li>Lijst</li>
</ul>
<div class="fence">
#RenderBody()
</div>
My problem concerns the return key. Whenever I press the return key my inserted value in the input( type=text) tag is lost.
For instance I type New York and want to get result in NY , my field is empty.
If I type it in and use my submit button everything is fine. Can anyone help me here?
You don't need any javascript for this. Simply use HTML helpers to generate your search form:
#using (Html.BeginForm("LocationSearch", "SomeController", FormMethod.Get, new { #class = "navbar-search" }))
{
<div class="icon-search icon-white"></div>
#Html.TextBox("searchstring")
<input type="submit" value="Search" />
}
You could change the type to submit rather than button and this will set the button to default.
Return key submits your form and in your case your page will refresh. Try to prevent this default action. There are plenty of tricks for that!