jQuery onclick method doesn't work twice - javascript

I have 2 onclick methods. The first one works fine but the second one doesn't works if i click first one, I need to refresh the page to run. Even if I do that, it only works once.
$(document).ready(function(){
$(".cart_add").on('click','.add_cart',function(){
var product_id = $(this).data("productid");
var size = $('ul#size').find('li.active a').data('value');
var qty = $('.qty-input').val();
var price = $('.special-price').data('price');
var name = $('h1.product-name').text();
var url = $(this).data("url");
$.post(url,{product_id:product_id,product_size:size,product_name:name,product_price:price,product_qty:qty},function(response){
$(".variant-1").html(response);
});
});
$(".secondary").on('click','.delete',function(){
var product_id = $(this).data("id");
var url = $(this).data("url");
$.post(url,{product_id:product_id},function(response){
$(".variant-1").html(response);
});
});
})

$("#CheckClick").click(function(){
alert("The paragraph was clicked.");
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<button class="btn btn-success" id="CheckClick">button</button>
Take ID Instead of Class check in side your code
or take your script inside function and call it on button click
function myFunction(){
alert("it's work well")
}
<input id="clickMe" type="button" value="clickme" onclick="myFunction();" />

you can try using onclick event from html button like`
function myFunction() {
alert('"hello"');
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<button onclick="myFunction()">Click me</button>
e`

Related

how to make an event happen when click a button on HTML by using javascript

I am trying to make HTML print out "Germany" when you click the button. But it is not working correctly. Is there something wrong in my code?
HTML
<input type="button" value="click!" onclick="shuffle();"/>
<div id="output"></div>
Javascript
(function(){
window.onload = function(){
alert("welcome to my trip record");
}
})();
var shuffle = function(){
var target = document.getElementById("output");
target.innerHTML = "Germany";
}
Remove the ; from your onclick
<input type="button" value="click!" onclick="shuffle()"/>
Try to use addEventListener for make event on button click
document.getElementById("myBtn").addEventListener("click", function(){
var target = document.getElementById("output");
target.innerHTML = "Germany";
});
here is the working jsfiddle:https://jsfiddle.net/jxjpzvvz/
You made two mistakes First mistake <input /> this is nothing. Second most common "function ();", the ";" Is wrong
Your corrected code
(function(){
window.onload = function(){
alert("welcome to my trip record");
}
})();
var shuffle = function(){
var target = document.getElementById("output");
target.innerHTML = "Germany";
}
<input type="button" value="click!" onclick="shuffle()"/>
<div id="output"></div>
I like to use DOM EventListener
window.onload = function(){
alert("welcome to my trip record");
}
document.getElementById("myBtn").addEventListener("click", function_t);
function function_t(){
var target = document.getElementById("output");
target.innerHTML = "Germany";
}
<input type="button" value="click!" id = "myBtn" >
<div id="output"></div>
<button id='btn_click' type="button">Click me!</button>
<div id="output"></div>
use button element for buttons, not input type button. we are not in the time of html 4.0 ;)
(function(){
window.onload = function(){
alert("welcome to my trip record");
}
})();
var shuffle = function(event){
var target = document.getElementById("output");
target.innerHTML = "Germany";
}
document.getElementById('btn_click').addEventListener('click', shuffle);
i'm fan of no js in the html tags directly, so i add a listener to the element

Input event not working if value is changed with jQuery val() or JavaScript

If I change the value of an input field programmatically, the input and change events are not firing. For example, I have this scenario:
var $input = $('#myinput');
$input.on('input', function() {
// Do this when value changes
alert($input.val());
});
$('#change').click(function() {
// Change the value
$input.val($input.val() + 'x');
});
<input id="myinput" type="text" />
<button id="change">Change value</button>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
The problem: The event is triggered when I type in the textfield, but not when I press the button. Is there a way to achieve this with some kind of event or otherwise without having to do it manually?
What I don't want to do: I could go through all my code to add a trigger or function call everywhere manually, but that's not what I'm looking for.
Why: The main reason I would like to do this automatically is that I have a lot of input fields and a lot of different places where I change these inputs programmatically. It would save me a lot of time if there was a way to fire the event automatically when any input is changed anywhere in my code.
Simple solution:
Trigger input after you call val():
$input.trigger("input");
var $input = $("#myinput");
$input.on('input', function() {
alert($(this).val());
});
$('#change').click(function() {
// Change the value and trigger input
$input.val($input.val() + 'x').trigger("input");
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<input id="myinput" type="text" />
<button id="change">Change value</button>
Specific solution:
As mentioned you don't want to trigger input manually. This solution triggers the event automatically by overriding val().
Just add this to your code:
(function ($) {
var originalVal = $.fn.val;
$.fn.val = function (value) {
var res = originalVal.apply(this, arguments);
if (this.is('input:text') && arguments.length >= 1) {
// this is input type=text setter
this.trigger("input");
}
return res;
};
})(jQuery);
See JSFiddle Demo
PS
Notice this.is('input:text') in the condition. If you want to trigger the event for more types, add them to the condition.
There are some ways on how to achieve it. Here, you can use the levelup HTML's oninput() event that occurs immediately when an element is changed and call the function.
<input id="myinput" type="text" oninput="sample_func()" />
<button id="change">Change value</button>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
.
var input = $("#myinput");
function sample_func(){
alert(input.val());
}
$('#change').click(function() {
input.val(input.val() + 'x');
});
Or this jQuery, input thing (just related to above example).
<input id="myinput" type="text" />
<button id="change">Change value</button>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
.
var input = $("#myinput");
input.on("input", function() {
alert(input.val());
});
$('#change').click(function() {
input.val(input.val() + 'x');
});
You can also use javascript setInterval() which constantly runs with a given interval time. It's only optional and best if you're doing time-related program.
<input id="myinput" type="text" />
<button id="change">Change value</button>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
.
var input = $("#myinput");
setInterval(function() { ObserveInputValue(input.val()); }, 100);
$('#change').click(function() {
input.val(input.val() + 'x');
});
jQuery listeners only work on actual browser events and those aren't thrown when you change something programmatically.
You could create your own miniature jQuery extension to proxy this so that you always trigger the event but only have to do in one modular place, like so:
$.fn.changeTextField = function (value) {
return $(this).val(value).trigger("change");
}
Then, just call your new function whenever you want to update your text field, instead of using jQuery's 'val' function:
$("#myInput").changeTextField("foo");
Here's a version working with a proxy function:
<!DOCTYPE html>
<html>
<head>
<title>Test stuff</title>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.2.2/jquery.min.js"></script>
</head>
<body>
<input id="myInput" type="text" />
<button id="myButton">Change value</button>
<script type="text/javascript">
$.fn.changeTextField = function (value) {
return $(this).val(value).trigger("change");
}
$( document ).ready(function() {
var $input = $("#myInput");
$input.on("change", function() {
alert($input.val());
});
$('#myButton').click(function() {
$("#myInput").changeTextField("foo");
});
});
</script>
</body>
</html>
For reference, this question has really already been answered here:
Why does the jquery change event not trigger when I set the value of a select using val()?
and here: JQuery detecting Programatic change event
Looks like there's no way, other than using .trigger().
Let's try the same thing using .change() event:
var $input = $("#myinput");
$input.on('change paste keyup', function() {
alert($(this).val());
});
$('#change').click(function() {
$input.val($input.val() + 'x').trigger("change");
});
<input id="myinput" type="text" />
<button id="change">Change value</button>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
Or you need to trigger it manually:
$('#change').click(function() {
$input.val($input.val() + 'x').trigger("input");
});
Snippet
var $input = $("#myinput");
$input.on('input', function() {
alert($(this).val());
});
$('#change').click(function() {
$input.val($input.val() + 'x').trigger("input");
});
<input id="myinput" type="text" />
<button id="change">Change value</button>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
Trigger didn't work for. Creating an event and dispatching with native JavaScript did the work.
Source: https://stackoverflow.com/a/41593131/6825339
<script type="text/javascript">
$.fn.changeTextField = function (value) {
return $(this).val(value).dispatchEvent(new Event("input", { bubbles: true });
}
$( document ).ready(function() {
var $input = $("#myInput");
$input.on("change", function() {
alert($input.val());
});
$('#myButton').click(function() {
$("#myInput").changeTextField("foo");
});
});
</script>
var $input = $('#myinput');
$input.on('input', function() {
// Do this when value changes
alert($input.val());
});
$('#change').click(function() {
// Change the value
$input.val($input.val() + 'x');
});
<input id="myinput" type="text" />
<button id="change">Change value</button>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.6.0/jquery.min.js"></script>
$input.val($input.val() + 'x')
$input.trigger('change');
The change event only fire when input blur.
Try this
$('#input').trigger('change');

Disabling html button using JavaScript won't POST

I have this Javascript and HTML code for my button:
function lockoutSubmit(button) {
var oldValue = button.value;
button.setAttribute('disabled', true);
button.value = '...processing...';
setTimeout(function(){
button.value = oldValue;
button.removeAttribute('disabled');
}, 3000)
}
<button style="margin-right:-160px;" type="submit" name="gen" onclick="lockoutSubmit(this)" class="btn btn-danger btn-block">Generate account!</button>
The code works fine for disabling the button for 3 seconds but the button is no longer posting to "gen".
Change the innerHTML instead of the value and bind the parameters to the settimeout instead of relying on the context.
Also button value might not be what you think it is:
http://www.w3schools.com/tags/att_button_value.asp
<html>
<head>
<script>
function _Unlock(){
var tB = document.getElementById('gen');
tB.removeAttribute('disabled');
tB.innerHTML = 'Generate account!';
localStorage.setItem('Lock', 0);
}
function Unlock(){
var tS = localStorage.getItem('Lock');
if (tS != '1') _Unlock()
else{
setTimeout(function(e, v){
_Unlock()
}, 3000)
}
}
function setToLock(){
localStorage.setItem('Lock', 1);
}
</script>
</head>
<body onload = 'Unlock()'>
<!-- Do you have a form and is it setup correctly? -->
<form action = '' method = 'post' id = 'myForm' onsubmit = 'setToLock()'>
<button id = 'gen' type = 'submit' name = 'gen' disabled = 'disabled'>...processing...</button>
<form>
</body>
</html>

Javascript: a variable contains value but Firebug says it is null

When i click on the button, nothing happens. Firebug says that "TypeError: btnNew is null"
My Javascript code is:
function addNewItem(){
alert("Test")
};
var btnNew = document.getElementById("btnAdd");
btnNew.onclick = addNewItem;
And the html is:
<input type = "text" id = "input">
<button id = "btnAdd">New item</button>
How come btnNew is null if its value is document.getElementById("btnAdd") ?
function addNewItem(){
alert("Test")
}
window.onload = function() {
var btnNew = document.getElementById("btnAdd");
btnNew.onclick = addNewItem;
}
<input type = "text" id = "input">
<button id = "btnAdd">New item</button>
You have to execute your js code after the document is loaded.
In window.onload or $document.ready() if you use jquery.
See window.onload vs $(document).ready() for differences.
you could use body onload event
see the code bellow
<!DOCTYPE html>
<html>
<body onload="myFunction()">
<input type = "text" id = "input">
<button id = "btnAdd">New item</button>
<script>
function myFunction() {
function addNewItem(){
alert("Test")
};
var btnNew = document.getElementById("btnAdd");
btnNew.onclick = addNewItem;
}
</script>
</body>
</html>

how to save a button

I want to save this button so that when i close the browser and reopen it i still is white.
I tried a lot but i just don't get the solution.
<script>
function save(){
var storeButton = document.getElementById("testButton1");
localStorage.setItem("button", storeButton)
}
function load(){
var storedButton = localStorage.getItem("button");
if(storedButton){
document.getElementById("testButton1") = storedButton;
}
}
</script>
<body onload="load()">
<input class="blue" type="button" id="testButton1" value="click me to turn white" style="background-color:blue" onclick="changeBlue(this)">
<input type="button" id="testButton" value="Save" onclick="save()"/>
</body>
You cannot save the button itself since local storage only stores strings.
Instead, save the information that you need in the form of a string (in this case, the color):
function save() {
var storeButton = document.getElementById("testButton1");
localStorage.setItem("buttonColor", storeButton.style.backgroundColor);
}
function load() {
var color = localStorage.getItem("buttonColor");
if (color) {
document.getElementById("testButton1").style.backgroundColor = color;
}
}

Categories