Hi I have the following code.
<input id="input1" type="text">
<input id="input2" type="text">
<input id="input3" type="text">
// ... so on up to 12.
my code
var $j = jQuery.noConflict();
$j(document).ready(function ($) {
var i, id;
for (i = 1; i != 13; ++i) {
id = "input" + i;
$(myFunc).on("change", function() {
this.value += " tab";
});
}
);
I am getting memory leak on input1, input2 ... according to drip.
How can i solve this.
If you are only trying to run this 12 times, I would do (notice the less than vs not-equal operation):
for (i = 1; i < 13; ++i) {
Also, where is myFunc defined? Maybe you're trying to do:
$(id).on("change", function() {
this.value += " tab";
});
One other thing, and I don't know if this is still an issue, in some browsers, jQuery use to have a problem setting a value on an input where there was no value attribute define.
<input id="input1" type="text" value="" />
What are you trying to do? doing a loop to set id to input1-12, but your on.('change') eventlistener doesn't even use the 'id' variable?
Are you trying to listen for change on any of your inputs and add " tab" to it when it changes? If so
$('input').on('change', function() {
$(this).attr('value') += " tab";
});
will suffice.
Related
I have a simple problem storing and passing a variable from one function to another. My script should work like this:
<input type="text" id="ip1" >
<input type="button" id="check_button" value="checking" onclick="check_text()">
<input type="button" id="write_button" value="write" onclick="write()">
<p id="ag"></p>
If somebody enters a value in the input field "ip1" and presses the "check_button", the value should be stored in a variable. This variable should be written in the innerHTML of "ag" when the "write_button" is clicked.
This is my JS. I am aware that this cannot work, I just don't know how to do it properly. I found similar problems but the solution always seems to complex for a beginner like myself to understand. A very easy solution would be very much appreciated!
function check_text() {
var ui = document.getElementById('ip1').value;
}
function write() {
document.getElementById('ag').innerHTML = ui;
}
You should declare variable outside the function:
it must work
var ui = 0;
function check_text() {
ui = document.getElementById('ip1').value;
}
function writeL() {
document.getElementById('ag').innerHTML = ui;
}
<input type="text" id="ip1" >
<input type="button" id="check_button" value="checking" onclick="check_text()">
<input type="button" id="write_button" value="write" onclick="writeL()">
<p id="ag"></p>
There are of course more than one way to process your value. The Snippet below uses the HTMLFormControlsCollection. Details are commented in the Snippet. BTW, I had to get rid of one of the buttons, it would probably hinder your understanding rather than aid it. It's better to visualize what's happening by watching the console.
SNIPPET
/***NOTE: Any comment having a pencil icon: ✎
|| means that the expression/statement is there...
||...to show an alternate way. Although they...
||...aren't used in the functions, they can be...
||...used instead of it's counterpart.
*/
function processData() {
// Reference the <form> by id or...
var form1 = document.getElementById('form1');
// ✎
/*1*/
console.log('1. This is ' + form1.id + '\n');
/*...or by HTMLFormControlsCollection...
||...reference <form> as the first <form>...
||...the .forms is an array-like object...
||...the [0] is the index indicating which...
||...<form> it's referring to. This is easily...
||...determined since there's only one <form>...
||...on the page.
*/
var formA = document.forms[0];
/*2*/
console.log('2. This is ' + formA.id + '\n');
// We'll continue using the HTMLFormControlsCollection
/* This is using previously declared formA to...
||...reference it's .elements property. The...
||...elements property is like the .forms...
||...except that it refers to a <form>'s...
||...field form elements like <input> and ...
||...<output>
*/
var formUI = formA.elements;
/*3*/
console.log('3. This is an ' + formUI + '\n');
// We can get the number of form control elements
var qty = formUI.length;
// ✎
/*4*/
console.log('4. form1 has ' + qty + ' form control elements\n');
/* Get the value of text1 by using the object formUI...
||...the name of <input>, and the .value property.
*/
var TXT1 = formUI.text1.value;
/*5*/
console.log('5. The value of text1 is ' + TXT1 + '\n');
/* We can get the same result by referencing <input>...
|| ...by it's index position in the formUI object...
|| This expression is getting the value of the first...
||...form field element of the <form> or formUI object
*/
var TXTA = formUI[0].value;
// ✎
/*6*/
console.log('6. The value of Text1 is still ' + TXTA + '\n');
/* Return the value of TXT1
|| This function returns a value, so it can be...
||...assigned to a var as a value and it can be...
||...passed through another function like a...
||...parameter.
*/
return TXT1;
}
/* This will pass a value...
||...reference the <output>...
||...and set <output> value to...
||...given value
*/
function displayData(value) {
var output1 = document.getElementById('output1');
output1.value = value;
}
/* When button1 is clicked...
||...store the return of processData() in a var...
||...then pass that var to displayData() function
*/
document.getElementById('button1').onclick = function(event) {
var VAL = processData();
displayData(VAL);
}
input {
font: inherit
}
<form id='form1' name='form1'>
<input type="text" id="text1" name='text1'>
<input type="button" value="display" id='button1'>
<br/>
<output id="output1" name='output1'></output>
</form>
You can do it easily with jQuery like this:
var enteredValue = "";
$("#check_button").on("click", function() {
enteredValue = $("#ip1").val();
});
$("#write_button").on("click", function() {
$('#store_value').html(enteredValue);
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input type="text" id="ip1" />
<input type="button" id="check_button" value="checking" />
<input type="button" id="write_button" value="write" />
<p id="store_value"></p>
So I am creating a web app that will do comparisons for products on the same page. Each time a person adds a new product they have the option to adjust some of the input fields. Each product has the exact same attributes such as the class and name. I may be able to append something on to each ID but there is a good chance that as each form is added to this page, it could possibly have a repeated ID. Yes I know that is not proper HTML but it works anyway. So my question is that how would I be able to re-use this same function without having to have one for each specific form that is added?
I have a sample of what I would be doing here:
<form>
<input type="text" id="the_input_id" class="formField1" placeholder="formField1">
<input type="text" id="the_input_id1" class="formField2" placeholder="formField2">
<input type="text" id="total" class="total" placeholder="total">
</form>
<form>
<input type="text" id="the_input_id" class="formField1" placeholder="formField1">
<input type="text" id="the_input_id1" class="formField2" placeholder="formField2">
<input type="text" id="total" class="total" placeholder="total">
</form>
Script:
$(function() {
$('.formField1,.formField2').blur(function() {
updateTotal();
});
var updateTotal = function () {
var input1 = parseInt($('.formField1').val()) || 0;;
var input2 = parseInt($('.formField2').val()) || 0;;
if(!input2){
$('.total').val($('.formField1').val()) || 0;;
}
if(!input1){
$('.total').val($('.formField2').val()) || 0;;
}
else {
$('.total').val(input1 + input2) || 0;;
}
};
var output_total = $('.total');
var total = input1 + input2;
output_total.val(total);
});
So basically, as each form is added, allow it to use that function and keep the outputs separate?
Fiddle
i'm not 100% sure what your trying to do with the particular script, but i can see what you want to do in an over-all pattern sense.
something like this should work:
$(function() {
$("form").on("blur", "input", function(e){
updateTotal(e.target.form);
});
function updateTotal (root) {
var input1 = parseInt($('.formField1', root).val()) || 0;;
var input2 = parseInt($('.formField2', root).val()) || 0;;
if(!input2){
$('.total', root).val($('.formField1', root).val()) || 0;;
}
if(!input1){
$('.total', root).val($('.formField2', root).val()) || 0;;
}
else {
$('.total', root).val(input1 + input2) || 0;;
}
var output_total = $('.total', root);
var total = input1 + input2;
output_total.val(total);
}
});
the big idea is to pass a container to the function and use that container in all jQuery dom searches inside the function by passing it as a 2nd parameter to $, after the css selector.
EDIT: i made a better binder using $.on() to hit forms not yet added to the dom when this code is executed.
i have code that can be use for subtract and additional textbox values using javascript and it is working but problem is that javascript again and again executed function whenever onfocus textbox i want only one time javascript should be executed function?
javascript function again and again additional onMouseOver="return B(0);"
javascript function again and again subtraction onfocus="return C();"
javascript function again and again additional onfocus="return D();"
function getObj(objID){
return document.getElementById(objID);
}
function B(){
var advanceBox = document.getElementById('advance');
var originalValue = advanceBox.value;
advanceBox.onfocus = function() {
this.value = parseFloat(originalValue, 10) +
parseFloat(document.getElementById('recamt').value, 10);
return false;
};
}
function C() {
getObj("balance").value=parseFloat(getObj("total").value || 0)-
(parseFloat(getObj("advance").value || 0)) ;
getObj("balance").value=parseFloat(getObj("balance").value || 0)-
(parseFloat(getObj("discount").value)||0) ;
return false;
}
function D() {
getObj("total").value=parseFloat(getObj("total").value || 0)+
(parseFloat(getObj("openbal").value || 0)) ;
return false;
}
Opening Balance:<input class="input_field2"
type="text" name="openbal" id="openbal"><br />
Total:<input class="input_field2" type="text"
readonly name="total" id="total" value="5000"><br />
Advance:<input class="input_field2" type="text"
readonly name="advance" id="advance" value="500"
onMouseOver="return B(0);"><br />
Balance:<input class="input_field2" readonly type="text"
name="balance" id="balance" onfocus="return C();"><br />
Rem Amount:<input class="input_field2" type="text"
name="recamt" id="recamt"><br />
Discount: <input class="input_field2"
style="background-color:#FFF !important;"
type="text" name="discount" id="discount" >
You could have:
var executedAlready = false;
An inside functions B and C have:
if(executedAlready != true){ executedAlready = true; }
else { return; }
Or maybe you could detach the events instead? I guess there are a few different ways to do this.
What the other answers tell you that the "quickest" way to get results is to make your functions only execute once.
You can do that like this:
Make a flag (just a variable that knows if your function has been triggered already).
When executing your functions, first check on this flag.
Here's an example how to do it with function B():
(Note: I didn't change your function, don't wanna get into that now)
// setup fired as false
var hasBFired = false;
function B(){
// if B is true, we do nothing
if (hasBFired) {
return;
// else if it is not true, basically only the first time you call this, flip the flag and execute the rest of the code.
} else {
hasBFired = true;
}
var advanceBox = document.getElementById('advance');
var originalValue = advanceBox.value;
advanceBox.onfocus = function() {
this.value = parseFloat(originalValue, 10) +
parseFloat(document.getElementById('recamt').value, 10);
return false;
};
Now, repeat the same with C and D functions (setup two more flags).
This is not the best way - it's not good to setup global objects and stuff, but since you probably aren't getting any side library in, it will help you solve your issue for now. For long term solution, you should use an Event library (like YUI Event) and have it handle attaching and detaching actions to onfocus events for you.
you can use one or more flag(s) :
in the begenning of the page :
<script>
var flag = false;
</script>
and on your element:
<div .... onMouseOver="if(!flag) { flag = true; return B(0);}" > .... </div>
same for onFocus...
So I've got code that looks like this:
<input class="messageCheckbox" type="checkbox" value="3" name="mailId[]">
<input class="messageCheckbox" type="checkbox" value="1" name="mailId[]">
I just need Javascript to get the value of whatever checkbox is currently checked.
EDIT: To add, there will only be ONE checked box.
None of the above worked for me but simply use this:
document.querySelector('.messageCheckbox').checked;
For modern browsers:
var checkedValue = document.querySelector('.messageCheckbox:checked').value;
By using jQuery:
var checkedValue = $('.messageCheckbox:checked').val();
Pure javascript without jQuery:
var checkedValue = null;
var inputElements = document.getElementsByClassName('messageCheckbox');
for(var i=0; inputElements[i]; ++i){
if(inputElements[i].checked){
checkedValue = inputElements[i].value;
break;
}
}
I am using this in my code.Try this
var x=$("#checkbox").is(":checked");
If the checkbox is checked x will be true otherwise it will be false.
in plain javascript:
function test() {
var cboxes = document.getElementsByName('mailId[]');
var len = cboxes.length;
for (var i=0; i<len; i++) {
alert(i + (cboxes[i].checked?' checked ':' unchecked ') + cboxes[i].value);
}
}
function selectOnlyOne(current_clicked) {
var cboxes = document.getElementsByName('mailId[]');
var len = cboxes.length;
for (var i=0; i<len; i++) {
cboxes[i].checked = (cboxes[i] == current);
}
}
This does not directly answer the question, but may help future visitors.
If you want to have a variable always be the current state of the checkbox (rather than having to keep checking its state), you can modify the onchange event to set that variable.
This can be done in the HTML:
<input class='messageCheckbox' type='checkbox' onchange='some_var=this.checked;'>
or with JavaScript:
cb = document.getElementsByClassName('messageCheckbox')[0]
cb.addEventListener('change', function(){some_var = this.checked})
$(document).ready(function() {
var ckbox = $("input[name='ips']");
var chkId = '';
$('input').on('click', function() {
if (ckbox.is(':checked')) {
$("input[name='ips']:checked").each ( function() {
chkId = $(this).val() + ",";
chkId = chkId.slice(0, -1);
});
alert ( $(this).val() ); // return all values of checkboxes checked
alert(chkId); // return value of checkbox checked
}
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>
<input type="checkbox" name="ips" value="12520">
<input type="checkbox" name="ips" value="12521">
<input type="checkbox" name="ips" value="12522">
Use this:
alert($(".messageCheckbox").is(":checked").val())
This assumes the checkboxes to check have the class "messageCheckbox", otherwise you would have to do a check if the input is the checkbox type, etc.
<input class="messageCheckbox" type="checkbox" onchange="getValue(this.value)" value="3" name="mailId[]">
<input class="messageCheckbox" type="checkbox" onchange="getValue(this.value)" value="1" name="mailId[]">
function getValue(value){
alert(value);
}
None of the above worked for me without throwing errors in the console when the box wasn't checked so I did something along these lines instead (onclick and the checkbox function are only being used for demo purposes, in my use case it's part of a much bigger form submission function):
function checkbox() {
var checked = false;
if (document.querySelector('#opt1:checked')) {
checked = true;
}
document.getElementById('msg').innerText = checked;
}
<input type="checkbox" onclick="checkbox()" id="opt1"> <span id="msg">Click The Box</span>
If you're using Semantic UI React, data is passed as the second parameter to the onChange event.
You can therefore access the checked property as follows:
<Checkbox label="Conference" onChange={(e, d) => console.log(d.checked)} />
Surprised to see no working vanilla JavaScript solutions here (the top voted answer does not work when you follow best practices and use different IDs for each HTML element). However, this did the job for me:
Array.prototype.slice.call(document.querySelectorAll("[name='mailId']:checked"),0).map(function(v,i,a) {
return v.value;
});
If you want to get the values of all checkboxes using jQuery, this might help you. This will parse the list and depending on the desired result, you can execute other code. BTW, for this purpose, one does not need to name the input with brackets []. I left them off.
$(document).on("change", ".messageCheckbox", function(evnt){
var data = $(".messageCheckbox");
data.each(function(){
console.log(this.defaultValue, this.checked);
// Do something...
});
}); /* END LISTENER messageCheckbox */
pure javascript and modern browsers
// for boolean
document.querySelector(`#isDebugMode`).checked
// checked means specific values
document.querySelector(`#size:checked`)?.value ?? defaultSize
Example
<form>
<input type="checkbox" id="isDebugMode"><br>
<input type="checkbox" value="3" id="size"><br>
<input type="submit">
</form>
<script>
document.querySelector(`form`).onsubmit = () => {
const isDebugMode = document.querySelector(`#isDebugMode`).checked
const defaultSize = "10"
const size = document.querySelector(`#size:checked`)?.value ?? defaultSize
// 👇 for defaultSize is undefined or null
// const size = document.querySelector(`#size:checked`)?.value
console.log({isDebugMode, size})
return false
}
</script>
Optional_chaining (?.)
You could use following ways via jQuery or JavaScript to check whether checkbox is clicked.
$('.messageCheckbox').is(":checked"); // jQuery
document.getElementById(".messageCheckbox").checked //JavaScript
To obtain the value checked in jQuery:
$(".messageCheckbox").is(":checked").val();
In my project, I usually use this snippets:
var type[];
$("input[name='messageCheckbox']:checked").each(function (i) {
type[i] = $(this).val();
});
And it works well.
if i run the same code for IE every thing is fine i am getting the value of selectedId where as for firefox and chrome it is giving values Undefine.
----------------- code -------------------------------
<html>
<head>
<script type="text/javascript">
function createSelected()
{
var value;
var theForm = document.hell;
for (var i = 0; i < theForm.length; i++)
{
var e = theForm.elements[i];
if ((e.type == "hidden") && (e.value == "false"))
{
console.log("the value of selected IDS="+e.selectedId);
if (e.selectedId!= undefined )
{
Value = ", "+e.selectedId;
}
}
}
console.log( Value);
}
</script>
</head>
<body>
<form name="hell">
<h1>This working only with IE not with FireFox and Crome </h1>
<br/>
<br/>
<input type="hidden" selectedId="heyya1" name="item1" value="false">h1</input>
<input type="hidden" selectedId="heyya2" name="item2" value="false">h2</input>
<input type="hidden" selectedId="heyya3" name="item3" value="false">h3</input>
<input type="hidden" selectedId="heyya4" name="item4" value="false">h4</input>
<input type="hidden" selectedId="heyya5" name="item5" value="false">h5</input>
<input type="hidden" selectedId="heyya6" name="item6" value="false">h6</input>
<input type="button" onclick=createSelected() value="find the values"></input>
</form>
</body>
---------------------------code end-----------------------------------------
please help in in this why cant we use other parameter( like Selectedid inside HTML tag) in FireFox like we can do it in IE.
thanks in advance..
In Chrome (sorry, I'm using a computer that doesn't have FF, and I'm not going to install it just for this question) it works if you use .getAttribute(). So:
// replace
e.selectedId;
// with
e.getAttribute("selectedId");
Or, in your function:
var id = e.getAttribute("selectedId");
console.log("the value of selected IDS="+id );
if (id != null)
{
value += ", "+id;
}
Also, note that JavaScript is case sensitive, so your variable value is not the same as Value, and you were saying Value = where you probably meant value +=. And you may want to use quotes around your element attributes: onclick="createSelected()".
Try reading the selectedId as below. Use getAttribute method
alert("the value of selected IDS="+e.getAttribute('selectedId'));