Javascript: how to change form fields value with single click - javascript

I'm trying to set the value of three different input text fields with an onclick function.
I have an image that has this code...
<img src="images/delete_row.png" width="25" onClick="clearRow(0);" />
And I have three input text fields that all have the id of "0".
When I click my image I want to set the value of all three fields to empty.
Can someone please help me write a function that can do this?
Thanks!

First, you need your id values to be different. You should never have the same ID twice on the same page. So lets use this as the example HTML:
<input type="text" id="name_0" name="name" />
<input type="text" id="phone_0" name="phone" />
<input type="text" id="email_0" name="email" />
You could use this JavaScript function:
<script type='text/javascript'>
function clearRow(id){
var name = document.getElementById('name_' + id),
phone = document.getElementById('phone_' + id),
email = document.getElementById('email_' + id);
// Clear values
name.value = phone.value = email.value = "";
}
</script>
And your img tag would remain unchanged:
<img src="images/delete_row.png" width="25" onClick="clearRow(0);" />

I have three input text fields that
all have the id of "0".
This is entirely wrong. In a document you can't have element with the same id. Either use a name or a classname for these textfields and make their ids different.
<script type="text/javascript">
function Change()
{
var elems = document.getElementsByName ( "myfields");
for ( var i = 0;i < elems.length; i++)
{
elems[i].value = "";
}
}
</script>
<input name="myfields" type="text" id="txt1" />
<input name="myfields" type="text" id="txt2" />
<input name="myfields" type="text" id="txt3" />
<img onclick="Change();" alt="test" src="yourimagpath" />

<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.3.2/jquery.min.js"></script>
<script>
$(document).ready(function() {
$('#pic').click(function() {
alert('Clicked on pic - resetting fields')
$('.field').val('')
})
}
</script>
<img id="pic" src="image.png">
<input class="field" value="1">
<input class="field" value="2">
<input class="field" value="4">
<input class="field" value="5">
<input class="field" value="6">
<input class="field" value="7">
<input class="field" value="8">
<input class="field" value="9">
<input class="field" value="10">

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/>

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)

generate and show password

i have a form with a html table.
my table is :
<table>
<tr>
<td>
<input type="text" name="password[]"/>
</td>
<td>
<input type="radio" value="1" onchange="generatePassword()"/>Short<br />
<input type="radio" value="2" onchange="generatePassword()"/>Medium<br />
<input type="radio" value="3" onchange="generatePassword()" />Long
</td>
<tr>
</table>
In my code, there is a button at the bottom and when it is clicked, it clones the table row. So, i dont know number of rows or number of password fields in my table. Because of clonning the row, i could not give id to my password field. So, I couldnt decide how to reach a text box without id. But i need to show my generated password in password field.
What you can do. You can find an input field from generatePassword like this:
function generatePassword(inp) {
var textbox = inp.parentNode.parentNode.cells[0].getElementsByTagName('input')[0];
textbox.value = 'password ' + inp.value;
}
You would also change markup a little. Add name attribute to radio buttons and reference current input with this:
<input type="radio" name="generate" onchange="generatePassword(this)" value="1" />
Demo: http://jsfiddle.net/BHb3N/
You could use Classes instead of an ID.
HTML
<input type="text" class="myPassword" value="test" name="password[]" />
<input type="text" class="myPassword" value="test" name="password[]" />
<input type="text" class="myPassword" value="test" name="password[]" />
JS
var passwords = document.getElementsByClassName('myPassword') || document.querySelectorAll('myPassword'); //querySelectorAll for IE <= 8
for (var i = 0; i < passwords.length; i++) {
console.log(passwords[i].value);
}
Use .getElementsByName instead of id:
document.getElementsByName('password[]')[0].value="anyvalue";
Fiddle1
OR
Use .getElementsByTagName
document.getElementsByTagName('input')[0].value="anyvalue";
Fiddle2
New fiddle in response to comment

Trying to set an html attribute to a javascript variable

I have a variable "count" in javascript and a radio button that I want to depend on that variable. There is a button to generate more radio buttons, which is why I need their name attributes to differ.
My code:
var count = 1;
function newForm(){
...<input name=count type="radio" value="Website" />...
}
But it's just setting the name of each additional radio button to "count" rather than the number "count" represents.
Here's the whole code:
var count = 1;
function newForm(){
var newdiv = document.createElement('div');
newdiv.innerHTML = '<div class="line"></div><br><input type="text" name="Name"
class="field" placeholder="Full Event Name" /><br><input type="text" name="Location"
placeholder="Event Location" class="field" /><br> <input type="text" name="Date"
placeholder="Event Date" class="field" /> <br> <input type="text" name="End"
placeholder="Event End Date (If Applicable)" class="field" /> <br> <input type="text"
name="Time" placeholder="Event Time" class="field" /> <br> <input type="text"
name="Tags"
placeholder="Relevant Tags" class="field" /> <br> The info is from: <input name=count
type="radio" value="Tweet" checked="" />Tweet <input name=count type="radio"
value="Website"
/>Website <input name=count type="radio" value="Tweet and Website" /> Tweet and
Website';
if(count < 10) {
document.getElementById('formSpace').appendChild(newdiv);
count++;
}
}
That newdiv.innerHTML string above is all on one line in the code, by the way.
If you're trying to create an element, use createElement() :
var count = 1;
function newForm(){
var input = document.createElement('input');
input.name = count;
input.type = 'radio';
input.value = 'Website';
}
in your long string of innerHTML you need to escape your "count" variable... otherwise it's just a string... i.e.
'<input name='+count+' type="radio" value="Tweet and Website" />';
That will make it work but as everyone else is mentioning - you really shouldn't embed long html strings like this.

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