how to pass the variable in jquery click event function - javascript

I want to Pass the variable with click event in jquery
var get=3;
$('#edit').click(function(event){
alert('You are getting:' + get);
}
please help me
html
<input type='submit' name='action' id='edit' />

You forgot the closing paranthesis.
Your javascript code should look like:
var get=3;
$('#edit').click(function(event){
alert('You are getting:' + get);
});

You have to initialize click even once document is loaded. Also you have syntax error in your code.
Try this one:
$(document).ready(function() {
var get=3;
$('#edit').click(function(event){
alert('You are getting:' + get);
});
});
<!DOCTYPE html>
<html>
<head>
<title></title>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.0/jquery.min.js"></script>
<script type="text/javascript">
$(document).ready(function() {
var get=3;
$('#edit').click(function(event){
alert('You are getting:' + get);
});
});
</script>
</head>
<body>
<input type='submit' name='action' id='edit' />
</body>
</html>

HTML button
<button id='my_button' type='button' data-id='1' data-values='1' value='6' data-whatever='20'>My button</button>
Jquery
$('#my_button').bind('click', function() {
var value = $(this)val();
var whatever = $(this).data('whatever');
var id = $(this).data('id');
var values = $(this).data('values');
console.log(value);
console.log(whatever);
console.log(id);
console.log(values);
});
Open Firefox > Inspect Element > Console Tab.
Load the codes
Click the button
See response

Initiate everything after document is ready.
$(document).ready(function() {
var get = 3;
$('#edit').click(function(event){
alert('You are getting:' + get);
});
});
also don't use event handlers until you need it.

try:
$(document).ready(function() {
var get=3;
$('#edit').on('click', function(event){
alert('You are getting:' + get);
}
});
html:
<input type="button" id="edit" />

You can do it like this:
$(document).ready(function() {
var get = 3;
$("#edit" ).bind("click", { key: get }, function(event){
// event.data.key will have value of get
});
});

Can you try like this,
<script type="text/javascript">
function test(ev) {
var id = $(ev).attr('id');
alert(id);
}
</script>
<input id="btn" type="button" value="click" OnClick="test(this);" />

try this.
html:
<input type="button" id="edit"><br/>
jquery:
$(document).ready(function(){
var get = 3;
$("#edit").on('click',function(){
alert("Value is: " + get);
//parameter value
});
});

Related

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');

Whats Wrong in this Code to generate SelectBoxes Dynamically?

<html>
<head>
<script src="http://code.jquery.com/jquery-latest.min.js"
type="text/javascript"></script>
<script>
function myf() {
alert("coming dude");
var numbersString = "1,2,3,4,5,6";
var data = numbersString.split(',');
var s = $("<select id=\"selectId\" name=\"selectName\" />");
for(var val in data) {
$("<option />", {value: val, text: data[val]}).appendTo(s);
}
s.appendTo("#msj_form");
}
</script>
</head>
<body >
<form id="msj_form" >
<button id="add" value="add" onclick="myf()">ADD</button>
</form>
</body>
</html>
While Clicking on ADD button the selbox is generating but its disappering immediatly..whats wrong in my code
While Clicking on ADD button the selbox is generating but its disappering immediatly..whats wrong in my code
Because after your function is called the form is submitted, so what you will need to do is prevent form submission.
Try this:
<html>
<head>
</head>
<body>
<form id="msj_form" >
<button id="add" value="add">ADD</button>
</form>
<script src="http://code.jquery.com/jquery-latest.min.js" type="text/javascript"></script>
<script>
function myf(e) {
e.preventDefault(); // <-- make sure to add this
alert("coming dude");
var numbersString = "1,2,3,4,5,6";
var data = numbersString.split(',');
var s = $("<select id=\"selectId\" name=\"selectName\" />");
for(var val in data) {
$("<option />", {value: val, text: data[val]}).appendTo(s);
}
s.appendTo("#msj_form");
}
$('#add').on('click',myf);
</script>
</body>
</html>
If you'd like to learn more about preventDefault(), see here - https://developer.mozilla.org/en-US/docs/Web/API/Event/preventDefault
The problem is that your form is getting submitted by default, so to prevent that just use preventDefault() method. Here's my solution. Hope it helps!
function myf() {
alert("coming dude");
var numbersString = "1,2,3,4,5,6";
var data = numbersString.split(',');
var s = $("<select id=\"selectId\" name=\"selectName\" />");
for(var val in data) {
$("<option />", {value: val, text: data[val]}).appendTo(s);
}
s.appendTo("#msj_form");
}
$(document).ready(function(){
$("#msj_form").submit(function(event){
event.preventDefault();
myf();
});
});
<script src="http://code.jquery.com/jquery-latest.min.js"
type="text/javascript"></script>
<form id="msj_form" >
<button id="add" value="add" >ADD</button>
</form>

How to delete an appended message in jquery after you have already appended once clicking the same button?

I have looked through a lot of the already asked questions and cannot find it. I need the previous appended message to be deleted once you hit the submit button again. So this will let you choose your character that you type into the input field and then it will append a message bellow telling you that you choose x character. After that you can resubmit another character which I want, but I do not want the previous append to be there.
I tried to do a search function in javascript and if it was not equal to -1 then delete the first p in the div, but that did not work=/
Thanks for your help in advance.
html:
<!DOCTYPE html>
<html>
<head>
<title>Result</title>
<link rel='stylesheet' type='text/css' href='styles/main.css'/>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.3/jquery.min.js"></script>
<script type='text/javascript' src='jquery/script.js'></script>
</head>
<body>
<form class="" action="index.html" method="post">
Chose your character (human, orc, elf) : <br><br><input id='text' type="text" name="mess" value="">
<button id='button1' type="button" name="button" onclick="chooseChar()">Submit</button>
</form>
<br>
<div id="box_holder"></div>
<br><br>
<button id='button2' type='button' name='button2' onclick="redirect()">Start Your Adventure</button>
</body>
</html>
JS:
$(document).ready(function() {
$('#button1').click(function(){
var send = $("input[name=mess]").val();
$('#box_holder').append('<p>'+ 'You have chosen your character to be: '+send+'</p>');
});
$('input').css("color","blue");
});
chooseChar = function () {
var text = document.getElementById('text').value;
var text = text.toLowerCase();
if(text == 'human') {
$(document).ready(function() {
$('#button1').click(function(){
var div = $("#box_holder p").val();
var searchTerm = "You";
var searchDiv = div.search(searchTerm);
if (searchDiv != -1) {
$('div p').first().remove();
}
});
});
window.alert("HUMAN YOU ARE! (You may change your character at anytime)");
return;
} else if (text == 'orc') {
window.alert("ORC YOU ARE! (You may change your character at anytime)");
return;
} else if (text == 'elf') {
window.alert("ELF YOU ARE !(You may change your character at anytime)");
return;
} else {
window.alert("Start over! Please choose one of the characters above!");
$(document).ready(function(){
$('div').remove();
});
return;
}
$(document).ready(function() {
});
};
redirect = function() {
var text = document.getElementById('text').value;
var url = text+".html";
window.location.href = url;
}
So your variable send gets sent and then it clears out the input field with either of those functions
$(document).ready(function() {
$('#button1').click(function(){
$('#box_holder').children('p').remove(); <===========
or Either of these should work
$('#box_holder').empty(); <===========================
var send = $("input[name=mess]").val();
$('#box_holder').append('<p>'+ 'You have chosen your character to be: '+send+'</p>');
});
$('input').css("color","blue");
});
Instead of using append, try using html as follows
$('#box_holder').html('<p>'+ 'You have chosen your character to be: '+send+'</p>');
Here is a Plunkr to explain it a little better
$(document).ready(function() {
$('#button1').click(function() {
var send = $("input[name=mess]").val();
$('#box_holder').html('<p>' + 'You have chosen your character to be: ' + send + '</p>');
});
$('input').css("color", "blue");
});
chooseChar = function() {
var text = document.getElementById('text').value;
text = text.toLowerCase();
if (text == 'human') {
$(document).ready(function() {
$('#button1').click(function() {
var div = $("#box_holder p").val();
var searchTerm = "You";
var searchDiv = div.search(searchTerm);
if (searchDiv != -1) {
$('div p').first().remove();
}
});
});
window.alert("HUMAN YOU ARE! (You may change your character at anytime)");
return;
} else if (text == 'orc') {
window.alert("ORC YOU ARE! (You may change your character at anytime)");
return;
} else if (text == 'elf') {
window.alert("ELF YOU ARE !(You may change your character at anytime)");
return;
} else {
window.alert("Start over! Please choose one of the characters above!");
$(document).ready(function() {
$('div').remove();
});
return;
}
$(document).ready(function() {
});
};
redirect = function() {
var text = document.getElementById('text').value;
var url = text + ".html";
window.location.href = url;
}
<!DOCTYPE html>
<html>
<head>
<script data-require="jquery#2.1.4" data-semver="2.1.4" src="http://code.jquery.com/jquery-2.1.4.min.js"></script>
<link rel="stylesheet" href="style.css" />
<script src="script.js"></script>
</head>
<body>
<form class="" action="index.html" method="post">
Chose your character (human, orc, elf) :
<br />
<br />
<input id="text" type="text" name="mess" value="" />
<button id="button1" type="button" name="button" onclick="chooseChar()">Submit</button>
</form>
<br />
<div id="box_holder"></div>
<br />
<br />
<button id="button2" type="button" name="button2" onclick="redirect()">Start Your Adventure</button>
</body>
</html>
You have to remember, the append() function appends the content on the selected component. The html() function replaces all content inside of it.
Hope it helps

onclick radio button fadeout body and redirect

<div id="language-container">
<form id="language_radio">
<input type="radio" value="//domain.tld/page.php?lang=02" name="language" id="alb">
<label for="alb">Shqip</label>
<input type="radio" value="//domain.tld/page.php?lang=03" name="language" id="eng">
<label for="eng">English</label>
</form>
</div>
<script type="text/javascript">
$("#language_radio input[type=radio]").change(function(event) {
event.preventDefault();
newLocation = $(this).val();
$("body").fadeOut(800, newpage);
});
</script>
What I'm trying to accomplish is, when a radio button is selected, I want to fade out the entire body, and then redirect to another page.
However, I can't seem to get it to do anything. It won't fade out or redirect.
How can do I fix it (newb to JS) :)?
You can use:
$("html").fadeOut();
as such:
<script type="text/javascript">
$("#language_radio input[type=radio]").change(function(event) {
event.preventDefault();
// This variable is useless
// You can remove it if it's not
// being used
newLocation = $(this).val();
$("html").fadeOut(800, function() {
// Redirect to the newLocation here
// similar behavior as clicking on a link
window.location.href = newLocation;
});
});
</script>
try :
<script type="text/javascript">
$("#language_radio input[type=radio]").change(function(event) {
event.preventDefault();
newLocation = $(this).val();
$("html").fadeOut(800, function() {
window.location.href = newLocation;
});
});
</script>
you can do this by
$("#language_radio input[type=radio]").change(function(event) {
event.preventDefault();
$("body").fadeOut(1000,function(){
window.location.href = $(this).val();
})
});
jsfiddle

Change variable value when checkbox is checked/unchecked

I was trying to change the value of an variable according to the status of an checkbox
here is my code sample
<script type="text/javascript">
if(document.getElementByType('checkbox').checked)
{
var a="checked";}
else{
var a="not checked";}
document.getElementById('result').innerHTML ='result '+a;
</script>
<input type="checkbox" value="1"/>Checkbox<br/>
<br/>
<span id="result"></span>
Can you please tell me whats the problem with this code.
Try this:
if (document.querySelector('input[type=checkbox]').checked) {
Demo here
Code suggestion:
<input type="checkbox" />Checkbox<br/>
<span id="result"></span>
<script type="text/javascript">
window.onload = function () {
var input = document.querySelector('input[type=checkbox]');
function check() {
var a = input.checked ? "checked" : "not checked";
document.getElementById('result').innerHTML = 'result ' + a;
}
input.onchange = check;
check();
}
</script>
In your post you have the javascript before the HTML, in this case the HTML should be first so the javascript can "find it". OR use, like in my example a window.onload function, to run the code after the page loaded.
$('#myForm').on('change', 'input[type=checkbox]', function() {
this.checked ? this.value = 'apple' : this.value = 'pineapple';
});
try something like this
<script type="text/javascript">
function update_value(chk_bx){
if(chk_bx.checked)
{
var a="checked";}
else{
var a="not checked";
}
document.getElementById('result').innerHTML ='result '+a;
}
</script>
<input type="checkbox" value="1" onchange="update_value(this);"/>Checkbox<br/>
<span id="result"></span>
Too complicated. Inline code makes it cool.
<input type="checkbox" onclick="yourBooleanVariable=!yourBooleanVariable;">
For those who tried the previous options and still have a problem for any reason, you may go this way using the .prop() jquery function:
$(document.body).on('change','input[type=checkbox]',function(){
if ($(this).prop('checked') == 1){
alert('checked');
}else{
alert('unchecked');
}
This code will run only once and check initial checkbox state. You have to add event listener for onchange event.
window.onload = function() {
document.getElementByType('checkbox').onchange = function() {
if(document.getElementByType('checkbox').checked) {
var a="checked";
} else {
var a="not checked";
}
document.getElementById('result').innerHTML ='result '+a;
}
}

Categories