How to fix onclick Function is not working using JavaScript [duplicate] - javascript

This question already has answers here:
Click event doesn't work on dynamically generated elements [duplicate]
(20 answers)
Closed 2 years ago.
Anyone can help me? this is my problem. When I tried to click the button using this function $(".btn_cellophane").on("click",function(){}); I did not get any response or even the error. I guess the onclick function is not working. Here's my code below.
METHOD CALLING
$(".btn_cellophane").on("click",function(){
alert("Tester true");
if($(this).hasClass("btn-warning")){
$(this).removeClass("btn-warning");
$(this).addClass("btn-success");
// add_amount_for_cellophane();
}else if($(this).hasClass("btn-success")){
$(this).addClass("btn-warning");
$(this).removeClass("btn-success");
// add_amount_for_cellophane();
}
});
CONTENT DISPLAY
var html_cellophane = "";
$.each(data, function(key,product){
$.each(product.sizes, function(pro_id,variant){
if(variant.prod_type == 1){
var label = (variant.size+" "+variant.unit).toUpperCase();
var var_id = variant.variant_id;
var price = variant.price;
html_cellophane += '<div>'+
'<label>Cellophane ('+price+' pesos)</label>'+
'</div>'+
'<br/>'+
'<div style="width: 100%;">'+
'<button type="button" class="btn btn-warning btn_cellophane" id="cp_id_btn" data-var_id="'+var_id+'" data-qty="'+1+'" data-price="'+price+'">1</button>'+
'<button type="button" class="btn btn-warning btn_cellophane" id="cp_id_btn" data-var_id="'+var_id+'" data-qty="'+2+'" data-price="'+price+'">2</button>'+
'<button type="button" class="btn btn-warning btn_cellophane" id="cp_id_btn" data-var_id="'+var_id+'" data-qty="'+3+'" data-price="'+price+'">3</button>'+
'<button type="button" class="btn btn-warning btn_cellophane" id="cp_id_btn" data-var_id="'+var_id+'" data-qty="'+4+'" data-price="'+price+'">4</button>'+
'<button type="button" class="btn btn-warning btn_cellophane" id="cp_id_btn" data-var_id="'+var_id+'" data-qty="'+5+'" data-price="'+price+'">5</button>'+
'<hr>'+
'</div>';
}
});
});
$('.btn_cellophane_div ').html(html_cellophane);

You've created the button dynamically. So while you are attaching the event listener the element doesn't exists till then. So you have to use event delegation for working the click event.
Just change your event listener like this-
$(document).on("click",".btn_cellophane", function(){});

Related

Unable to get Data Attribute value of dynamically generated buttons in jQuery

I am new to JavaScript and was trying to figure our how to access data attribute values of dynamically generated buttons.
I was passing my ID coming from the Database to "data-id" attribute. Below is the dynamically generated code for my buttons
<button class='btn btn-sm btn-primary aButton' data-id='1234'></button>
<button class='btn btn-sm btn-primary aButton' data-id='12345'></button>
<button class='btn btn-sm btn-primary aButton' data-id='12346'></button>
<button class='btn btn-sm btn-primary aButton' data-id='12347'></button>
Now i wanted to access these buttons onclick using jquery to perform some actions. Below is my code for that
$(document).on('click', '.aButton', () => {
let id = $(this).attr('data-id');
console.log(id);
})
The above console gives me "undefined" with the thick arrow function. When I tried to do the same with function () {}, it gave me the dynamic ID stored in the data attribute of the button.
What is happening with this? Is there a better approach to get a dynamic ID of button on click.
Thank you all in advance.
Have a nice day :)
When you use arrow function () => {} then jquery don't know what this refers to so use:
$(document).on('click', '.aButton', (e) => {
let id = $(e.target).attr('data-id') || $(e.target).closest('.aButton').attr('data-id');
console.log(id);
})
Demo
$(document).on('click', '.aButton', (e) => {
let id = $(e.target).attr('data-id') || $(e.target).closest('.aButton').attr('data-id');
console.log(id);
})
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<button class='btn btn-sm btn-primary aButton' data-id='1234'><i>testers</i></button>
<button class='btn btn-sm btn-primary aButton' data-id='12345'></button>
<button class='btn btn-sm btn-primary aButton' data-id='12346'></button>
<button class='btn btn-sm btn-primary aButton' data-id='12347'></button>

How to get multiple values using JSTL tags?

I have this button:
<button type="button" class="btn btn-danger" id="deleteuserbtn" value="${usr.idUser}" onclick="deleteUser(this.value)">Delete</button>
That calls the function deleteUser once the button is clicked.
I would like to know how to send more than one value at the same time.
For example, if I want to send the idUser and the userName, how can I do it?.
I tried this but it's not working:
<button type="button" class="btn btn-danger" id="deleteuserbtn" value="${usr.idUser, usr.userName}" onclick="deleteUser(this.value)">Delete</button>
I expect to receive the values in the same jsp page:
function deleteUser(val1, val2) {
alert(val1);
alert(val2);
}
You can simply pass your values under your function under '' quotes else it will give you error not defined.So your button code will look like below :
<button type="button" class="btn btn-danger" value="something" id="deleteuserbtn" onclick="deleteUser(this.value ,'${usr.idUser}','${usr.userName}')">
Delete</button>
Demo Code :
function deleteUser(val1,val2,val3){
alert("val :"+val1 +" "+val2+" "+val3);
}
<button type="button" class="btn btn-danger" id="deleteuserbtn" value="something" onclick="deleteUser(this.value,'${usr.idUser}','${usr.userName}')">
Delete</button>

Cannot change the innerHTML element

I want to change a button inside a td tag (see at the bottom an example).
var tableEntryButton = document.getElementById('slButton' + message.content[1])
delivers correctly the td element I am looking for:
<td id="slButtonAudi" data-value="false">
<button id="slButtonActive" class="btn btn-outline-success btn-sm" type="button" onclick="handleClickOnSSButton(this)">Start</button>
</td>
Here my function that should make the change possible.
Here I distinguish by the ID within the button tag what change I can apply (remove the current start/stop button and add the button with the opposite function)
var tableEntryButton = document.getElementById('slButton' + message.content[1])
let activeButton = '<button id="slButtonActive" class="btn btn-outline-success btn-sm" type="button" onclick="handleClickOnSSButton(this)">Start</button>'
let inactiveButton = '<button id="slButtonInactive" class="btn btn-outline-warning btn-sm" type="button" onclick="handleClickOnSSButton(this)">Stop</button>'
if (tableEntryButton.innerHTML.includes('slButtonActive')) {
tableEntryButton.removeChild(tableEntryButton.firstChild)
tableEntryButton.innerHTML = inactiveButton
}
else {
tableEntryButton.removeChild(tableEntryButton.firstChild)
tableEntryButton.innerHTML = activeButton
}
The if/else allocation works correctly.
It appears that only the changes within the if/else statement are somehow not being applied.
To clarify it here an example.
If this is given:
<td id="slButtonAudi" data-value="false">
<button id="slButtonActive" class="btn btn-outline-success btn-sm" type="button" onclick="handleClickOnSSButton(this)">Start</button>
</td>
it should be changed to that:
<td id="slButtonAudi" data-value="false">
<button id="slButtonInactive" class="btn btn-outline-warning btn-sm" type="button" onclick="handleClickOnSSButton(this)">Stop</button>
</td>
You are not using the innerHtml correctly.
I made you an example that will do exactly what you asked in your last example.
if (tableEntryButton.innerHTML.includes('slButtonActive')) {
//Get the children button.
let button = tableEntryButton.querySelector("#slButtonActive");
if (button) {
tableEntryButton.removeChild(button);
tableEntryButton.innerHTML += inactiveButton;
}
}
Here is the working fiddle:
https://jsfiddle.net/vrtfoh9q/20/
Some documentation:
https://plainjs.com/javascript/manipulation/append-or-prepend-to-an-element-29/
https://www.w3schools.com/js/js_htmldom_nodes.asp
Hope it helps!
you can access children by children property in HTML element and use innerHTML once time like this:
HTML
<div id="div1">
<button id="btn1Active">Active</button>
</div>
JS
let divTarget = document.getElementById('div1'),
child = divTarget.children[0],
btnActive = '<button id="btn1Active">Active</button>',
btnInactive = '<button id="btn1Inactive">Inactive</button>'
if (child.id == 'btn1Active') divTarget.innerHTML = btnInactive
else divTarget.innerHTML = btnActive
CodePen example
https://codepen.io/bragamonte/pen/PBLojZ

How to get data from attributes then disable buttons accordingly

I have run a bit of problem with our user interface, here's my code:
I have a button here inside a
<button class="btn btn-info" type="button" id="btnSubmit" data-btn="{{ row[1] }}" data-id="{{ row[2] }}" data-toggle="modal" data-target="#myModal" contenteditable="false" disabled='disabled'> Pay</button>
I have been using row[2] from another function and it worked, so this time i used row[1] to evaluate data. The condition is that
when the row[1] of that row is empty the button would be disabled and would be colored to btn btn-danger and the text would be
made to "Paid" however thorugh my attempts I only made everything disabled or perhaps the last entry only as disabled. Here's my latest attempt:
<script type="text/javascript">
$(document).ready(function() {
var button = document.getElementById('btnSubmit');
var id = button.dataset.id;
$('#btnSubmit').attr('data-btn').onkeyup(function() {
if($(this).val() != '') {
$('#btnSubmit').prop('disabled', true);
}
else{
$('#btnSubmit').prop('disabled', false);
}
});
});
</script>
And its disabling all buttons. I just want the bytton to be enabled when its empty and disabled if its empty, and again as Ive said would be colored to btn btn-danger and the text would be made to "Paid" how do I do this in this case?
I've read the documentations and everything but it didn't work for some reasons. I also tried having an invisible input and getting its id but no luck. Please help
Okay... Assuming that data-bnt is the target element to check on keyup.
(I don't know what data-id is for...)
And that the target must not be empty to enable the submit button.
Then try this:
$(document).ready(function() {
var button = $('#btnSubmit');
var target = $('#'+button.data('btn'));
target.on("keyup",function(){
button.prop('disabled', ($(this).val() == '') ? true : false );
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input type="text" id="targetID">
<button
class="btn btn-info"
type="button"
id="btnSubmit"
data-btn="targetID"
data-toggle="modal"
data-target="#myModal"
contenteditable="false"
disabled='disabled'> Pay</button>

JavaScript Event Listener runs twice

As reference, please see my example in JSFiddle below. Every time somebody clicks on the plus button, a new row should be inserted below. This works fine except the fact that the amount of new rows inserted is always twice the amount of current existing rows. How can I avoid this strange behavior, or what's the reason for it? Please click the first rows button to see the issue.
http://jsfiddle.net/jrxeua6L/
var answers = [{
order: 1,
content: "placeholder"
}],
appendAnswer = function() {
answers.push({
order: answers.length + 1,
content: $(this).parent().prev().val()
});
$("#answers").empty();
$.each(answers, function(key, value) {
$("#answers").append('<div class="input-group"><input type="text" class="form-control" placeholder="Enter your answer"><span class="input-group-btn"><button type="button" class="btn btn-default" title="Add a question" data-action="add"><span class="glyphicon glyphicon-plus"></span></button><button type="button" class="btn btn-default" title="Delete this question" data-action="delete" disabled><span class="glyphicon glyphicon-trash"></span></button></span></div>');
$("#answers button[data-action='add']").one("click", appendAnswer);
});
};
$("#answers button[data-action='add']").one("click", appendAnswer);
Use event-delegation
$("#answers").on("click", "button[data-action='add']",appendAnswer);
The cause of your problem is that you are binding multiple events on same elements in the each loop, so remove the delegation there.
Remove this line below from the .each() loop
$("#answers button[data-action='add']").one("click", appendAnswer);
DEMO
Here is a working solution http://jsfiddle.net/jrxeua6L/4/
var answers = [{
order: 1,
content: "placeholder"
}],
appendAnswer = function() {
answers.push({
order: answers.length + 1,
content: $(this).parent().prev().val()
});
$("#answers").empty();
$.each(answers, function(key, value) {
$("#answers").append('<div class="input-group"><input type="text" class="form-control" placeholder="Enter your answer"><span class="input-group-btn"><button type="button" class="btn btn-default" title="Add a question" data-action="add"><span class="glyphicon glyphicon-plus"></span></button><button type="button" class="btn btn-default" title="Delete this question" data-action="delete" disabled><span class="glyphicon glyphicon-trash"></span></button></span></div>');
//$("#answers button[data-action='add']").on("click", appendAnswer);
});
};
$('body').on("click", "#answers button[data-action='add']", appendAnswer);
Change this line:
$("#answers button[data-action='add']").one("click", appendAnswer);
To this:
$("#answers button[data-action='add']").off("click").one("click", appendAnswer);

Categories

Resources