why i can't change value of a text field by javascript? - javascript

I try to get my tag by tag name and change thats value, can you help me to find why this not work?
var r_capacity=document.getElementsByName("capacity");
function expireOtherFildes(){r_capacity.value="";}
ID: <input type="text" name="id" class="textBox" onFocus="expireOtherFildes()"/>
capacity: <input type="text" name="capacity" value="xxx"/>

You need to use this:
var r_capacity=document.getElementsByName("capacity")[0];
document.getElementsByName("capacity") returns an nodeList.
The nodes can be accessed by index numbers.
var r_capacity=document.getElementsByName("capacity")[0];
function expireOtherFildes(){r_capacity.value="";}
ID: <input type="text" name="id" class="textBox" onFocus="expireOtherFildes()"/>
capacity: <input type="text" name="capacity" value="xxx"/>

document.getElementsByName returns array. You have access it by index.Refer below -
var r_capacity=document.getElementsByName("capacity");
function expireOtherFildes(){
r_capacity[0].value="";
}
ID: <input type="text" name="id" class="textBox" onFocus="expireOtherFildes()"/>
capacity: <input type="text" name="capacity" value="xxx"/>

document.getElementsByName() return an array of NodeList. You need to select the first index, or simply switch to document.getElementById()
var r_capacity=document.getElementsByName("capacity")[0];
//-^^^
console.log(r_capacity);
function expireOtherFildes(){r_capacity.value="";}
ID: <input type="text" name="id" class="textBox" onFocus="expireOtherFildes()"/>
capacity: <input type="text" name="capacity" value="xxx"/>

You need to use
var r_capacity = document.getElementsByName("capacity")[0];
because var r_capacity = document.getElementsByName("capacity"); it's returning a nodeList and you can access that taking use of the index which is 0:
var r_capacity = document.getElementsByName("capacity")[0];
console.log(r_capacity);
function expireOtherFildes() {
r_capacity.value = "";
}
ID:
<input type="text" name="id" class="textBox" onFocus="expireOtherFildes()" />capacity:
<input type="text" name="capacity" value="xxx" />
A better approach to do it would be to use querySelector(), this will prevent from getting a problem like you encountered:
var r_capacity = document.querySelector("input[name='capacity']");
console.log(r_capacity);
function expireOtherFildes() {
r_capacity.value = "";
}
ID:
<input type="text" name="id" class="textBox" onFocus="expireOtherFildes()" />capacity:
<input type="text" name="capacity" value="xxx" />

Related

Multiplication in jQuery dynamically

I am trying to make a multiplication function in jquery where which helps change the default value-based output.
For example - if I type the input#mainInput value then it will change all the inputs value base own his default value * input#mainInput and if the value == 'NaN' it will do dirent funcion.
Please help me how to I make this function in jQuery.
$(document).on('keyup', 'input#mainInput', function() {
thisParentQtyValueBox = $(this).val();
daughtersBoxValueAttr = $("input.input__bom").attr("inputid");
daughtersBoxValue = $("input#daughterInput_" + daughtersBoxValueAttr).val();
$("input#daughterInput_" + daughtersBoxValueAttr).val(thisParentQtyValueBox * daughtersBoxValue);
if ($("input#daughterInput_" + daughtersBoxValueAttr) == 'Nan') {
$("input#daughterInput_" + daughtersBoxValueAttr).val('3' * daughtersBoxValue)
}
});
//If
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<input id="mainInput" type="text" placeholder="Number" />
<br><br>
<input class="input__bom" id="daughterInput_1" type="text" placeholder="value" inputid="1" value="5" /><br/>
<input class="input__bom" id="daughterInput_2" type="text" placeholder="value" inputid="2" value="10" /><br/>
<input class="input__bom" id="daughterInput_3" type="text" placeholder="value" inputid="3" value="15" /><br/>
<input class="input__bom" id="daughterInput_4" type="text" placeholder="value" inputid="4" value="20" /><br/>
<input class="input__bom" id="daughterInput_5" type="text" placeholder="value" inputid="5" value="25" /><br/>
If I understand correctly, when the input is not a number, you want to do as if the input was 3.
Some issues in your code:
$("input.input__bom").attr("inputid") is always going to evaluate to 1, as only the first matching element is used. And it is strange to use this attribute value to then retrieve that element again via its id property.
You would need a loop somewhere so to visit each of the "input__bom" elements.
== 'Nan is never going to be true. You should in fact test the main input itself to see if it represents a valid number. For that you can use isNaN.
It is a bad idea to give these elements a unique id attribute. You can use jQuery to visit them each and deal with them. There is no need for such id attribute.
Don't use the keyup event for this, as input can be given in other ways than pressing keys (e.g. dragging text with mouse, or using the context menu to paste). Use the input event instead.
There is no good reason to use event delegation here on $(document). Just bind your listener directly the main input element.
Declare your variables with var (or let, const). It is bad practice to no do that (it makes your variables global).
It seems like the 5 "bom" input elements are not really intended for input, but for output. In that case the placeholder attribute makes no sense, and they should better be marked with the readonly attribute.
$("#mainInput").on('input', function() {
var mainInput = $(this).val();
var multiplier = +mainInput; // convert to number with unary +
// default value in case input is not a valid number, or is empty
if (Number.isNaN(multiplier) || !mainInput) {
multiplier = 3;
}
$('.input__bom').each(function() {
$(this).val( multiplier * $(this).data('value') );
});
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<input id="mainInput" type="text" placeholder="Number" />
<br><br>
<input class="input__bom" type="text" readonly data-value="5" value="5"><br/>
<input class="input__bom" type="text" readonly data-value="10" value="10"><br/>
<input class="input__bom" type="text" readonly data-value="15" value="15"><br/>
<input class="input__bom" type="text" readonly data-value="20" value="20"><br/>
<input class="input__bom" type="text" readonly data-value="25" value="25" /><br/>
You have to store the default value in the data attr so then it will not multiple by result value and it will multiple by your default value. for dynamic multiplication, you can use jquery each. check below code.
$(document).on('input', 'input#mainInput', function() {
thisParentQtyValueBox = parseInt( $(this).val() );
if( Number.isNaN( thisParentQtyValueBox ) ){
thisParentQtyValueBox = 3;
}
$('.input__bom').each(function(){
$(this).val( thisParentQtyValueBox * $(this).data('value') );
});
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<input id="mainInput" type="text" placeholder="Number" />
<br><br>
<input class="input__bom" id="daughterInput_1" type="text" placeholder="value" inputid="1" data-value ="5" value="5" /><br/>
<input class="input__bom" id="daughterInput_2" type="text" placeholder="value" inputid="2" data-value ="10" value="10" /><br/>
<input class="input__bom" id="daughterInput_3" type="text" placeholder="value" inputid="3" data-value ="15" value="15" /><br/>
<input class="input__bom" id="daughterInput_4" type="text" placeholder="value" inputid="4" data-value ="20" value="20" /><br/>
<input class="input__bom" id="daughterInput_5" type="text" placeholder="value" inputid="5" data-value ="25" value="25" /><br/>

Call for multiple values to be displayed in textarea

I'm in the process of trying to create a simple input form web page using both HTML and JavaScript but I am stuck. What I am trying to do is to ask for the following and display them in the textarea:
-First Name
-Last Name
-CRN
-Professor Name
So far I am only able to get the First Name to show on the Results box but no luck with the other. Could use some help, thanks in advance.
My CODE looks like this:
// initialize the counter and the array
var numbernames=0;
var names = new Array();
function SortNames() {
// Get the name from the text field
thename=document.theform["firstn"].value
// Add the name to the array
names[numbernames]=thename;
// Increment the counter
numbernames++;
document.theform.sorted.value=names.join("\n");
}
<form name="theform">
First Name:
<input type="text" name="firstn" size="10" /><p>
Last Name:
<input type="text" name="lastn" size="10" /><p>
CRN:
<input type="text" name="crn" size="10" /><p>
Professor:
<input type="text" name="prof" size="10" />
<input type="button" name="addname" value="Submit"
onclick="SortNames();">
<h2>Results:</h2>
<textarea cols="50" rows="10" name="sorted">
</textarea>
</form>
Here's a complete different, but more readable approach.
I get all inputs of type text.
I get the textarea that is the target.
loop throug all inputs getting it's value.
inside loop, after getting the value, set it to the textarea
Take a look running the snippet below
// initialize the counter and the array
function SortNames() {
var inputs = document.querySelectorAll('input[type="text"]');
var txtArea = document.querySelector('[name="sorted"]');
//loop the text inputs
inputs.forEach(function(elem){
var valueOf = elem.value;
txtArea.value += valueOf + '\n'; //concat the value
});
}
<form name="theform">
First Name:
<input type="text" name="firstn" size="10" /><p>
Last Name:
<input type="text" name="lastn" size="10" /><p>
CRN:
<input type="text" name="crn" size="10" /><p>
Professor:
<input type="text" name="prof" size="10" />
<input type="button" name="addname" value="Submit" onclick="SortNames();">
<h2>Results:</h2>
<textarea cols="50" rows="10" name="sorted"></textarea>
</form>
EDIT
If you REALLY want to keep the way you were doing, here's a solution:
1. Push the values from the inputs directly to the array, then set the value inside the textarea.
// initialize the counter and the array
var names = new Array();
function SortNames() {
names.push(document.theform["firstn"].value);
names.push(thename=document.theform["lastn"].value);
names.push(thename=document.theform["crn"].value);
names.push(thename=document.theform["prof"].value);
document.theform.sorted.value=names.join("\n");
}
<form name="theform">
First Name:
<input type="text" name="firstn" size="10" /><p>
Last Name:
<input type="text" name="lastn" size="10" /><p>
CRN:
<input type="text" name="crn" size="10" /><p>
Professor:
<input type="text" name="prof" size="10" />
<input type="button" name="addname" value="Submit"
onclick="SortNames();">
<h2>Results:</h2>
<textarea cols="50" rows="10" name="sorted">
</textarea>
</form>
Changed the tags to more semantic and functional tags. Used the HTMLFormControlsCollection API to set/get form controls. The output is a Template Literal.
Details Commented in Demo
Demo
// Reference the top form
const reg = document.forms.registration;
// Reference the bottom form
const dis = document.forms.display;
// Collect all inputs from top form
const f = reg.elements;
// When top form is clicked...
reg.onclick = function(event) {
// Collect the data from each input and store it in an Object
const student = {
First: f.first.value,
Last: f.last.value,
CRN: f.crn.value,
Prof: f.prof.value
};
// Call function
displayData(event, student);
}
function displayData(event, student) {
// Reference the textarea
const view = dis.elements.sorted;
// if the element that was clicked had [name=add]...
if (event.target.name === 'add') {
/* Set the textarea's value to a Template Literal with
|| interpolated values from the student Object.
*/
view.value += `
First: ${student.First}
Last.: ${student.Last}
CRN..: ${student.CRN}
Prof.: ${student.Prof}
~~~~~~~~~~~~~~~~~~~`;
// Otherwise quit
} else {
return false;
}
}
input,
label {
font: inherit;
display: inline-block;
}
label {
width: 20%
}
[type=text] {
width: 75%;
}
[type=reset] {
margin: 5px 0 0 85%;
}
<!DOCTYPE html>
<html lang=”en”>
<head>
<title></title>
</head>
<body>
<form id="registration">
<fieldset id='set0'>
<legend>Registration</legend>
<label>First Name: </label>
<input type="text" name="first" size="10" /><br>
<label>Last Name: </label>
<input type="text" name="last" size="10" /><br>
<label>CRN: </label>
<input type="text" name="crn" size="10" /><br>
<label>Professor: </label>
<input type="text" name="prof" size="10" /><br>
<input type="reset" name="add" value="Submit">
</fieldset>
</form>
<form id='display'>
<fieldset id='set1'>
<legend>View Data</legend>
<textarea cols="50" rows="10" name="sorted">
</textarea>
</fieldset>
</form>
</body>
</html>

how do i clone a multiple html input field with jquery

i have a complex div with input field somewhat like this
<input type="text" name="firstname">
<input type="text" name="lastname">
<input type="text" name="email">
<input type="text" name="address">
<div id="section_toClone">
<input type="text" name="tree[tree1][fruit]">
<input type="text" name="tree[tree1][height]">
<input type="checkbox name tree[tree1][color] value="green">Green </input>
<input type="checkbox name tree[tree1][color] value="yellow">yellow </input>
</div>
<button id="add_more"> Add </button>
now when someone click on add i want something like this to happen
<input type="text" name="tree[tree1][fruit]">
<input type="text" name="tree[tree1][height]">
<input type="checkbox name tree[tree1][color] value="green">Green </input>
<input type="checkbox name tree[tree1][color] value="yellow">yellow </input>
<input type="text" name="tree[tree2][fruit]">
<input type="text" name="tree[tree2][height]">
<input type="checkbox name tree[tree2][color] value="green">Green </input>
<input type="checkbox name tree[tree2][color] value="yellow">yellow </input>
<input type="text" name="tree[tree3][fruit]">
<input type="text" name="tree[tree3][height]">
<input type="checkbox name tree[tree3][color] value="green">Green </input>
<input type="checkbox name tree[tree3][color] value="yellow">yellow </input>
and so on..... but my script only clone doesnt change the value of tree from tree1 to tree2 to tree3 and so on.... here is my jquery script
$('#add_more').click(function(){
$("#section_toClone").clone(true).insertBefore("#add_more").find('input').val("").val('');
});
how do i increment that automatically?? i want to mention one more thing in actual html code. it has more then 3 input and 3 checkbox field
Don't even bother putting the numbers into the array keys. Just let PHP take care of it itself:
<input name="tree[fruit][]" value="foo" />
<input name="tree[fruit][]" value="bar" />
<input name="tree[fruit][]" value="baz" />
Any [] set which DOESN'T have an explicitly specified key will have one generated/assigned by PHP, and you'll end up with
$_POST['tree'] = array(
0 => 'foo',
1 => 'bar',
2 => 'baz'
);
As long as your form is generated consistently, browsers will submit the fields in the same order they appear in the HTML, so something like this will work:
<p>#1</p>
<input name="foo[color][]" value="red"/>
<input name="foo[size][]" value="large" />
<p>#2</p>
<input name="foo[color][]" value="puce" />
<input namke="foo[size][]" value="minuscule" />
and produce:
$_POST['color'] = array('red', 'puce');
| |
$_POST['size'] = array('large', 'minuscule');
But if you start mixing the order of the fields:
<p>#3</p>
<input name="foo[color][]" value="red"/>
<input name="foo[size][] value="large" />
<p>#4</p>
<input namke="foo[size][] value="minuscule" />
<input name="foo[color][] value="puce" />
$_POST['color'] = array('red', 'puce');
/
/
$_POST['size'] = array('minuscule', 'large');
Note how they're reversed.
I wouldn't post this without feeling a bit ashamed of how bad it is written, but the following solution does the trick. Badly.
var treeCount = 1;
$('#add_more').click(function(){
$("#section_toClone")
.clone(true)
.insertBefore("#add_more")
.find('input')
.val('')
.each(function(key,element){
var $element = $(element),
oldName = $element.attr('name'),
newName;
if(oldName){
newName = oldName.replace(/tree[0-9]+/, 'tree'+(treeCount+1));
$element.attr('name', newName);
}
else {
treeCount--;
}
})
.promise().done(function(){
treeCount++;
});
});
(please don't shoot me)

How do I use javascript to update the values of hidden input fields

I have the following fields:
First Name: <input type="text" id="tFName" name="tFName" maxlength="50" />
Last Name: <input type="text" id="tLName" name="tLName" maxlength="50" />
I want to use javaScript specifically dojo to update the value of the following hidden input fields:
<input type="hidden" name="tFName" value=""/>
<input type="hidden" name="tLName" value=""/>
what are some ways in Javascript and Dojo to accomplish this?
dojo.query('#tFName').val('Joe');
See the val() docs.
In plain Javascript, you can just set the .value property:
document.<form name>.tFName.value = <whatever>
document.<form name>.tLName.value = <whatever>
If we modify the html some (setting an ID on the hidden ones) we can:
First Name: <input type="text" id="tFName" name="tFName" maxlength="50" />
<input type="hidden" id="hiddenFName" name="tFName" value=""/>
var fName = dijit.byId("tFName");
var hFName = dijit.byId("hiddenFName");
hFName.attr("value", fName.attr("value"));
Try this: document.getElementsByName("tFName")[0].value ="abc";
document.getElementsByName("tLName")[0].value ="def";

Copy contents of one textbox to another

Suppose an entry is made in a textbox. Is it possible to retain the same entered text in a second text box? If so, how is this done?
<html>
<label>First</label>
<input type="text" name="n1" id="n1">
<label>Second</label>
<input type="text" name="n1" id="n1"/>
</html>
<script>
function sync()
{
var n1 = document.getElementById('n1');
var n2 = document.getElementById('n2');
n2.value = n1.value;
}
</script>
<input type="text" name="n1" id="n1" onkeyup="sync()">
<input type="text" name="n2" id="n2"/>
More efficiently it can be done as :
For the one who will see the post now should use best practices of javascript.
<script>
function sync(textbox)
{
document.getElementById('n2').value = textbox.value;
}
</script>
<input type="text" name="n1" id="n1" onkeyup="sync(this)">
<input type="text" name="n2" id="n2"/>
<html>
<script type="text/javascript">
function copy()
{
var n1 = document.getElementById("n1");
var n2 = document.getElementById("n2");
n2.value = n1.value;
}
</script>
<label>First</label><input type="text" name="n1" id="n1">
<label>Second</label><input type="text" name="n2" id="n2"/>
<input type="button" value="copy" onClick="copy();" />
</html>
Well, you have two textboxes with the same ID. An Id should be unique, so you should prbably change this.
To set the value from one text box to another a simple call to getElementById() should suffice:
document.getElementById("n1").value= document.getElementById("n2").value;
(assuming, of course you give your secodn text box an id of n2)
Tie this up to a button click to make it work.
This worked for me and it doesn't use JavaScript:
<form name="theform" action="something" method="something" />
<input type="text" name="input1" onkeypress="document.theform.input2.value = this.value" />
<input type="text" name="input2" />
</form>
I found the code here
Use event "oninput". This gives a more robust behavior. It will also trigger the copy function when you copy paste.
You can this way also used copy contents of one textbox to another
function populateSecondTextBox() {
document.getElementById('txtSecond').value = document.getElementById('txtFirst').value;
}
<label>Write Here :</label>
<input type="text" id="txtFirst" onkeyup="populateSecondTextBox();" />
<br>
<label>Will be copied here :</label>
<input type="text" id="txtSecond" />

Categories