Storing / passing a variable to another function - javascript

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>

Related

How do I use a form input number as a Javascript variable?

<form>
<input type="text" name="" value="">
</form>
//for loop used to calculate balance after payment(x) and interest
// the variable I want defined from the form input box
for(i = 6000; i>=10; i = i * (1+0.2/26)-x){
var x = 155;
document.write("Balance " + " $" + i + "<br/><br/>");
}
You could attach a pseudo class in your input element and then get the value inserted like below:
<input type="text" name="" value="" class="js-interest">
<script>
var ele = document.getElementsByClassName("js-interest")[0];
var value = parseFloat(ele.value);
</script>
You can try document.getElementById('input_id').value and then use parseInt to get it as an integer, as below:
var x = parseFloat(document.getElementsByName('number_box').value);
Also, the html must look something like this:
<form>
<input type="text" name="number_box" value="">
</form>
Optionally, instead of document.getElementsByName() you can use document.getElementById() or document.getElementsByClassName().
Update:
If I am not wrong
for(i = 6000; i>=10; i = i * (1+0.2/26)-x){
var x = 155;
document.write("Balance " + " $" + i + "<br/><br/>");
}
It seems like you are writing to the DOM inside a for loop don't do that calculate your ANS and then write to the DOM.
Also, don't read the data from input inside the loop. (You will be repeatedly reading and writing the data thats not good.)
Your for loop for(i = 6000; i>=10; i = i * (1+0.2/26)-x) is incrementing using some expression i = i * (1+0.2/26)-x (make sure it is bound to the condition and its not making the loop infinite)
You can select the value from the input field using the following code
x = parseInt(document.querySelector('form input[name="my_number"]').value);
document.querySelector it uses CSS style selector. So, to select the input field inside your form. I have added a name to the form as name="my_number"
<input type="text" name="my_number" value="">
now using the css selector form input[name="my_number"] it select the input field inside a form with name "my_number"
The whole Query selector that will return the input element is this,
document.querySelector('form input[name="my_number"]')
now to get the value of the input field you have to read the value property of the input field.
document.querySelector('form input[name="my_number"]').value
This will return your input value as string.
Now, we need to parse that string value to a Integer format.
We do that like this, (using parseInt)
parseInt(document.querySelector('form input[name="my_number"]').value)
I have added you code in a function named calc
function calc() {
var x = parseInt(document.querySelector('form input[name="my_number"]').value);
var ans= calculate_your_value(x);
document.write("Balance " + " $" + ans + "<br/><br/>");
}
I have fetched the answer from a function named get calculated answer and its good to do this way.
function calculate_your_value(x){
// calculate the ans the for loop seems buggy
//for (i = 6000; i >= 10; i = i * (1 + 0.2 / 26) - x) {}
return x; //dummy ans
}
It is called when you submit the form.
To do that I have added onsubmit='calc()' on your form tag.
<form onsubmit='calc()'>
Additionally, I have added this function that submits the form when you have pressed enter too (Just for fun) :)
document.onkeydown=function(){
if(window.event.keyCode=='13'){
calc();
}
}
It just listens for key down press and check if it is a enter key (keycode is 13)
and calls the same calc function.
function calc() {
var x = parseInt(document.querySelector('form input[name="my_number"]').value);
var ans= calculate_your_value(x);
document.write("Balance " + " $" + ans + "<br/><br/>");
}
document.onkeydown = function() {
if (window.event.keyCode == '13') {
calc();
}
}
function calculate_your_value(x){
// calculate the ans the for loop seems buggy
//for (i = 6000; i >= 10; i = i * (1 + 0.2 / 26) - x) {}
return x; //dummy ans
}
<form onsubmit='calc()'>
<input type="text" name="my_number" value="">
<input type="submit" id="submitbtn" />
</form>

How can I change a part of input's name via jquery?

I have such code in my view:
<div class="box">
<input type="text" name="product[size_ids][<%= size.id %>][quantity][1]" readonly class="product_quantity" placeholder="quantity from" value="1">
</div>
In my js I'd like to change [1] into [2] or [3] and so on after [quantity], depending on how many additional forms I create. How can I do that?
This is what I have in my JS:
var i = 1
$('.add_another_price_btn').click( function (e) {
e.preventDefault();
$(this).prev().clone().insertBefore($(this));
$(this).prev().find('.remove_another_price_btn').show();
$(this).prev().find('.product_quantity').removeAttr('readonly');
$(this).prev().find('.product_quantity').attr('value', '');
//This is what I tried, but it doesn't work properly.
$(this).prev().find('.product_quantity')
.attr('name', function() { return $(this).attr('name') + '['+ (i++) + ']' });
$('.remove_another_price_btn').click( function (ee) {
ee.preventDefault();
$(this).parent().parent().remove();
});
You can do a simple string operation with substr and lastIndexOf to replace the last part of the name.
// get input and name of input
var input = $("input");
var name = input.attr("name");
// change just the last part
name = name.substr(0, name.lastIndexOf("[")) + "[2]";
// set name back to input
input.attr("name", name);
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input type="text" name="product[size_ids][<%= size.id %>][quantity][1]" readonly class="product_quantity" placeholder="quantity from" value="1">
Save the clone
Break the name using substring or split and parseInt
Like this
var $clone = $(this).prev().clone(),
$prodQ = $clone.find('.product_quantity'),
name = $prodQ.attr("name"),
parts = name.split("quantity]["),
newName = parts[0]+"quantity][",
num = parseInt(parts[1],10); // or a counter
num++;
newName += num+"]";
$prodQ.removeAttr('readonly').attr('value', '').attr('name',newName);
$clone.insertBefore($(this));
$clone.find('.remove_another_price_btn').show();

dynamic name for an input with jQuery

I have an issue with automatic name for input, I'll try to explain what i need to do. i have an id, that I get it from an external function. I need to use this numeric id to create another function like that.
var id = 10; // this is the id (from external function)
var value = "n"+bar.toString(); // (I try to cast the id as string)
$("input[name="+value+"]").on('change', function() { // use the cast value to name my input.
alert($("input[name="+value+"]:checked", "#myForm").val());
});
When I try to do that I get undefined, but when I change the id like that var id ="10" I get the correct answer, but I have a numeric input. Please help me figure out how to solve this problem.
Did you want something like this? This is based on an assumption that you have checkboxes within a form!
var ids = [10, 20, 30, 11, 12];
$.each(ids, function(index, val) {
var id = val;
var value = "n" + id; // `.toString` is not required!
$("#myForm").find("input[name='"+value+"']").on('change', function() {
if ($(this).is(":checked")) {
alert( $(this).val() );
}
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<form id="myForm">
<input type="checkbox" name="n10" value="10" />
<input type="checkbox" name="n11" value="11" />
<input type="checkbox" name="n12" value="12" />
</form>
use this code no need for id.toString()
var id = getId(); // this is the id (from externel function)
var value = "n" + id;
$("input[name="+value+"]").on('change', function() {
alert($("input[name="+value+"]:checked").val()); //change this selector accordingly
});
function getId() {
return 10;
}
here is the fiddle
https://jsfiddle.net/rrehan/srhjwrz4/
Try below code:
var id = 10; // this is the id (from externel function)
var value = id.toString(); // (i try to cast the id as string)
console.log(value);
$("input[name="+value+"]").on('change', function() { // use the casted value to name my input.
alert($("input[name="+value+"]:checked", "#myForm").val());
});
Demo Link

Add a checkbox for the innerHTML in javascript

I have a page which contains a 10 items(formatted list).Here in this page I need to add check box for each item and add the item as the value to each check box.when the user click on the check box the selected value should be passed to a new page.Can anyone help me how to add a check box for the innerHTML in java script.
Code:
var newsletter=document.getElementById("block-system-main");
var districolumn=getElementsByClassName('view-id-_create_a_news_letter_',newsletter,'div');
if(districolumn!=null)
{
var newsletterall=newsletter.getElementsByTagName('li');
alert(newsletterall[0].innerHTML);
var all=newsletter.innerHTML;
newsletter.innerHTML="<input type='button' onclick='changeText()' value='Change Text'/>";
}
function changeText()
{
alert("dfgsdg");
}
I don't exactly understand what each part of your code is doing, but i'll try and give a general answer:
In your HTML, do something like this:
<form id="myForm" action="nextPage.com">
<div id="Boxes"></div>
</form>
Change the above names to wherever you want your checkboxes to be written.
And your function:
function changeText()
{
for(var i=0 ; i < newsletterall.length ; i++)
{
var inner = document.getElementById("Boxes").innerHTML;
var newBox = ('<input type="checkbox" name="item[]" value="' + newsletter[i] + '>' + newsletterall[i]);
document.getElementById("Boxes").innerHTML = inner + newBox;
}
document.getElementById("myForm").submit();
}
The last line of code submits the checkboxes automatically. If you don't want that, remove that line, and add a submit button to the form myForm.
​
$('ul​​​#list li').each(
function() {
var me = $(this),
val = me.html(),
ckb = $('<input type="checkbox" />');
ckb.click(function() {
var where=val;
window.location.href='http://google.com/?'+where;
});
me.html('');
me.append(ckb).append($('<span>'+val+'</span>'));
}
);​​​​

jQuery or Javascript to parse querystring on submit

This form has multiple choices through a checkbox. Eg. Pet You Own is a multiple choice and there are various options such as Cat, Dog, Mule etc.
Now by default, the querystring sent will look like:
?pet=dog&pet=cat&pet=mule
given all 3 are checked.
I need a way to parse this so that the querystring looks like:
?pet=dog,cat,mule
Another requirement is that, there are other parameters/inputs in the form so it needs to work in conjunction with other standard form inputs.
The format you're currently seeing is the conventional format. If your form fields were named pet[] rather than pet, your server would be able to interpret the result as an array.
Having said that, to actually do what you're requesting, you could reset the name attribute of your checkboxes, so that they won't be posted, and instead post a hidden field that holds the value of your checkboxes as a comma separated string:
$('#my-form').submit(function() {
var pets = [];
$('input[name=pet]:checked').each(function() {
pets.push($(this).val());
});
// stop checkboxes from being posted
$('input[name=pet]').attr('name','');
// have an input field be posted instead
$('#my-hidden-field')
.val(pets.join(','))
.attr('name', 'pet');
});
A bit of cleaning is needed but using this with plain JS you can acheive
<html>
<head>
<title>My Page</title>
<script>
function myFunction(){
var options = "";
if(document.getElementById("option1").checked){
options = options+"Milk";
}
if(document.getElementById("option2").checked){
options = options+",Butter";
}
if(document.getElementById("option3").checked){
options = options+",Cheese";
window.location = "end.html&options="+options
}
}
</script>
</head>
<body>
<div align="center"><br>
<input id="option1" type="checkbox" name="option1" value="Milk"> Milk<br>
<input id="option2" type="checkbox" name="option2" value="Butter" checked> Butter<br>
<input id="option3" type="checkbox" name="option3" value="Cheese"> Cheese<br>
<br>
</div>
Button to submit
</body>
</html>
I suggest you to do this job on server side. When your server receive this request, it will get an array which is called pet and has three element: dog,cat and mule. you can conjunction them easily.
====
I implement this with JavaScript:
var str = window.location.href;
var queryString = "", temp = {};
str = str.substring(str.lastIndexOf("?") + 1);
str.split("&").some(function(item) {
var tarr = item.split("=");
if(typeof temp[tarr[0]] == "undefined") {
temp[tarr[0]] = tarr[1];
} else if(typeof temp[tarr[0]] == "string") {
temp[tarr[0]] += "," + tarr[1];
}
});
// Make queryString
for(var i in temp) {
queryString += "&" + i + "=" + temp[i];
}
queryString = queryString.replace(/^./,"");
//
var href = window.location.href;
console.log("before:", href);
href = href.replace(/\?.*$/, "?");
// the url is that you want
console.log("after:", href + queryString);
//window.location.href = href + queryString;
OUTPUT:
before:
http://www.boutell.com/newfaq/creating/forcedownload.html?pet=dog&pet=cat&pet=mule&animal=camel
after:
http://www.boutell.com/newfaq/creating/forcedownload.html?pet=dog,cat,mule&animal=camel
Name your check boxes as p1, p2 etc. Have a hidden field in your form named 'pet'. Just before submit using JS, set the value of your hidden variable the way you need and return true.
function beforeSubmit() {
var p = '';
if($('#p1').attr('checked')==true) p += ',cat';
if($('#p2').attr('checked')==true) p += ',dog';
...
p = p.substring(1); // strip the , at 0
$('#pet').val(p);
return true;
}
and your form should be like:
<form ... onsubmit="return beforeSubmit()">
...
<input type="checkbox" name="p1" id="p1">Cat<br>
<input type="checkbox" name="p2" id="p2">Dog<br>
...
<input type="hidden" name="pet" id="pet" value="">
</form>

Categories