Clear a textbox when another is active (JavaScript) - javascript

I have some HTML with two textboxes:
<input id="tb1" type="text" name="textbox1">
<input id="tb2" type="text" name="textbox2">
I want some JavaScript that will remove any content in textbox2 if the user has clicked/tabbed inside textbox1 (and vice versa).
I'm still learning JavaScript, but I think I need something like the following:
$('#textbox1').focus(function(){
SOMETHING HERE TO CLEAR TEXTBOX2
});
Any help gratefully received!

Your focus event is not working properly. The should use the hashtag sign and the element id (not the name).
$('#tb1').focus(function(){
$('#tb2').val('');
});
Working pen:
https://codepen.io/Rechousa/pen/ddJXeq

You can do this by binding the focus event on both inputs and then clearing the value of the one not focused. Ex:
$('#tb1, #tb2').focus(function() {
$('#tb1, #tb2').not(this).val('');
})
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input id="tb1" type="text" name="textbox1">
<input id="tb2" type="text" name="textbox2">

Related

Move data from on input field to another and submit form

I am trying to get one input field that is higher up the page, move it's content to a form field at the bottom of the page and submit the form.
Please see what I have done here (doesn't work):
$('#move_down').click(function() {
$('#input_1').val($('#input_2').val())
});
<input type="text" id="input_1" value="">
<br>
<button id="move_down">Click Here</button>
<br>
<input type="text" id="input_2" value="">
<script src="//code.jquery.com/jquery-3.2.0.js"></script>
Moving the data is just the first part, I am also trying to get it to take the user down to the main form and submit it - is this possible with jQuery?
Updated the question to fix my silly error of omitting the ID selectors. Just need to figure out how to submit the form now.
You are right; just correct your query selector:
$('#move_down').click(function() {
$('#input_2').val($('#input_1').val())
});
http://jsfiddle.net/82x28ryr/4/
Missing the # prefix for id selector
Works fine doing
$('#move_down').click(function() {
$('#input_2').val($('#input_1').val())
});
<input type="text" id="input_1" value="">
<br>
<button id="move_down">Click Here</button>
<br>
<input type="text" id="input_2" value="">
<script src="//code.jquery.com/jquery-3.2.0.js"></script>
As for "moving down" you have only provided html in demo for 2 inputs. You need to update question with all relevant html in order to implement additional features

jQuery targeting selector by input type and form name

I want to target any input of text type belonging to a form of a specific name. Because the form will have numerous input fields, I don't want to target a particular input name, but rather, capture the blur (or focusout) event for any input[type="text"] occurring within the form wrap.
My present code, which doesn't work:
$( document ).ready(function() {
$('form[name="tax_form"] input[type="text"]').on("blur",function() {
alert($(this).val());
});
});
I answered my own question. Because the code sample is essentially correct, there is no need for multiple people to try to solve the unsolvable. The problem had something to do with where I placed the javascript code, and nothing to do with structure or syntax of the code, itself.
The way the event "change" works is what it sounds like you want. An event handler doesn't actually fire when the input is clicked or if text is keyed in, it fires when text is entered and then the input loses focus.
In the following Snippet the same selector you are using is delegated to the "change" event. You'll notice that the ['tax_form'] has 4 text inputs yet the last one is the only one working. The reason is because if an input isn't assigned a type attribute, then by default type is 'text". So when using a selector based on an input's type="text", you must keep that in mind. So if you are in full control of your HTML, make sure that each input has a type attribute with an explicit value, or use classes which is better IMO.
SNIPPET
$(document).ready(function() {
$('form[name="tax_form"] input[type="text"]').on("change", function() {
alert($(this).val());
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<form name='notIt'>
<fieldset>
<legend>Not a Tax Form</legend>
<input>
<input type="text">
<input>
<input type="text">
</fieldset>
</form>
<br/>
<br/>
<form name='stillNotIt'>
<fieldset>
<legend>Still not a Tax Form</legend>
<input type="text">
<input>
<input type="text">
<input>
</fieldset>
</form>
<br/>
<br/>
<form name='tax_form'>
<fieldset>
<legend>Tax Form</legend>
<input class='klass' value='TEXT INPUT BY DEFAULT'>
<input value='TEXT INPUT BY DEFAULT'>
<input name='text' value='TEXT INPUT BY DEFAULT'>
<input type='number'>
<input type='text' value='THIS ONE COUNTS'>
</fieldset>
</form>
Previous commentators were right, that my code was fine as-is. I took my selector code out of a header script file, and placed it at the bottom of my footer script, and it worked as expected.
In the end, it wasn't my code that was the problem, but rather something to do with where I placed it. Possibly other javascript or jQuery code stepping on it.
Your code should work fine. Here's a working example of it to prove it's working. The tax_form fields should console.log() on blur. The another_form should not.
$(function() {
$('form[name="tax_form"] input[type="text"]').on("blur",function() {
console.log($(this).val());
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<h1>Tax Form</h1>
<form name="tax_form">
<input type="text" name="first" value="first">
<input type="text" name="second" value="second">
<input type="text" name="third" value="third">
</form>
<h1>Another Form</h1>
<form name="another_form">
<input type="text" name="first2" value="first2">
<input type="text" name="second2" value="second2">
<input type="text" name="third2" value="third2">
</form>

Copy input field's value to multiple hidden fields... but with same ID's?

1) I have 3 input radio buttons with unique values.
For e.g.
<input type="radio" id="id1" value="This is first value" />
<input type="radio" id="id2" value="This is second value" />
<input type="radio" id="id3" value="This is third value" />
2) Next, I have 2 hidden form like this:
<form action="//mysite.com/process1.php"><input type="hidden" id="uniqueid" value=""></form>
<form action="//mysite.php/process2.php"><input type="hidden" id="uniqueid" value=""></form>
3) Based upon whichever radio button the user clicks, I need to copy its value to the value of both the above forms hidden field.
For e.g. If user clicks on radio with id1, then it's value "This is first value" should be copied to both the forms hidden field.
CONSTRAINTS:
1) Have to use javascript or jquery, no server side processing available.
2) Note: both the final forms have one input field, but with same id. This is a constraint.
3) Why? Because based on some other actions on the page, the user gets to see one of the 2 forms. The only difference between them is their action is unique. All fields are same.
WHAT I HAVE SO FAR:
Using this, I am able to copy the value from the radio button to a hidden field's value, but it only copies to a field with a UNIQUE ID.
var $unique = $("#unique");
$("#radio1").keyup(function() {
$unique.val(this.value);
});
$("#email").blur(function() {
$unique.val(this.value);
});
Can someone guide as to how can the value be copied to multiple input fields, but with same id's?(Yes, the id's of the initial radio buttons can be unique.)
Having two HTML elements with same ID is an error.
You cannot treat this as a constraint, this is NOT a valid HTML code and it will cause inconsistent behavior in different browsers.
Use classes instead:
<form action="//mysite.com/process1.php"><input type="hidden" class="uniqueid" value=""></form>
<form action="//mysite.php/process2.php"><input type="hidden" class="uniqueid" value=""></form>
And javascript:
var $unique = $(".uniqueid");
However, I couldn't find any #radio1 or #email in your code, are you sure you have the right selectors?
My recommendation for the JS will be: (Working jsFiddle)
var $unique = $(".uniqueid");
$('input[type="radio"]').click(function(){
$unique.val(this.value);
});
Notes for jsFiddle:
I've used click event instead of keyup (don't really understand why you used keyup here..).
I've given all radio buttons the same name so they will cancel each other out when selected.
I've turned the hidden fields to text so you could see the result.
<form action="//mysite.com/process1.php"><input type="hidden" class="uniqueid" id="uniqueid" value=""></form>
<form action="//mysite.php/process2.php"><input type="hidden" class="uniqueid" id="uniqueid" value=""></form>
var $unique = $("input[type=hidden].uniqueid");
$("#radio1").keyup(function() {
$unique.val(this.value);
});
$("#email").blur(function() {
$unique.val(this.value);
});
As said by others, id must be unique. Try using a data-attribute:
<form action="//mysite.com/process1.php">
<input type="hidden" data-shouldupdate="true" value="">
</form>
<form action="//mysite.php/process2.php">
<input type="hidden" data-shouldupdate="true" value="">
</form>
Now you can use that attribute as selector to do something like:
$('[data-shouldupdate]').val(this.value);
I agree with all other who posted that id have to be unique to have correct HTML document. So if it's possible I strictly recommend you to fix the HTML document to remove all duplicates.
I write my answer only for the case that you can't remove id duplicates because of some reason and you still have the same requirements. In the case you should change the line
var $unique = $("#uniqueid");
to
var $unique = $("*[id=uniqueid]");
The selector *[id=uniqueid] (or just [id=uniqueid]) works slowly as #uniqueid, but it allows you to get all elements with the specified id attribute value. So it works even in case of id duplicates on the HTML page.
The most simple solution is to give a same name to both inputs. Check this link jsfiddle to see a working example. The code used is the one given is below:
HTML:
<input type="radio" name="copiedValue" id="id1" value="This is first value" />
<input type="radio" name="copiedValue" id="id2" value="This is second value" />
<input type="radio" name="copiedValue" id="id3" value="This is third value" />
<form action="//mysite.com/process1.php"><input name="uniqueid" id="uniqueid" value=""></form>
<form action="//mysite.php/process2.php"><input name="uniqueid" id="uniqueid" value=""></form>
jQuery/javascript:
$("input:radio[name=copiedValue]").click(function() {
$("input[name=uniqueid]").val($(this).val());
});
The radio-buttons should have the same name. I removed the type="hidden" so u can see it working correctly.
Hope it useful!

Create new form fields with jQuery

I have a form which starts out with 2 text inputs. The standard scenario is the user enters a number in one field and his/her name in the other and then the page will be updated (not reloaded). But in some cases the user may want to enter several numbers which are connected to the same name and the way this will be implemented is by the user clicking an "add another" link next to the text box.
When the user clicks the "add another" link, the value from the textbox needs to be inserted into a new (dynamically created) text field and the text field where the user entered the number should be reset to default value. The user can enter 10 numbers this way before an alert is presented informing him/her about more efficient ways to do this operation.
I'm clueless as to how this is done (can it be done) jQuery and it would be great if someone can help out.
Here is the html I'm working with:
<div id="searchFields" class="control-group inlineForm">
<label for="regNr">Regnr</label> <input type="text" id="regNr" class="uprCase" placeholder="Regnr." size="6" maxlength="6">
<span class="addRegNr">add another</div>
<label for="poNr">PO.nr</label> <input type="text" id="poNr" placeholder="PO.nr." size="12" maxlength="12">
<input type="button" value="GET INFO" class="last" id="getBaseInf">
</div>
http://jsfiddle.net/RgKV9/
Cheers!
EDIT UPDATE
I've taken a liking to Aske G's example and have made some changes to it. Here is the new code I'm working with, jsfiddle.net/SDpfy Although I managed to do some minor changes to AskeG's code I cant figure out how to add unique ID's and individual delete links for each generated field that ends up in the basket. Also, how can I set the generated fields to readonly and animate them when they show up in the basket?
just add a click watcher to the span. Check this fiddle: http://jsfiddle.net/ranjith19/RgKV9/4/
I have done some basic changes. If you need custom names id's you should use a templating library and then append it
<div id="searchFields" class="control-group inlineForm">
<label for="regNr">Regnr</label> <input type="text" id="regNr" class="uprCase" placeholder="Regnr." size="6"
maxlength="6">
<label for="poNr">PO.nr</label> <input type="text" id="poNr" placeholder="PO.nr." size="12" maxlength="12">
<input type="button" value="GET INFO" class="last" id="getBaseInf">
<p></p>
</div>
<span class="addRegNr" style="display:inline">add another</span>
<script type="text/javascript">
$(document).ready(function () {
str_to_append = '<label for="regNr">Regnr</label> <input type="text" id="regNr" class="uprCase" placeholder="Regnr." size="6" maxlength="6">\
<label for="poNr">PO.nr</label> <input type="text" id="poNr" placeholder="PO.nr." size="12" maxlength="12">\
<input type="button" value="GET INFO" class="last" id="getBaseInf"><p></p>'
$(".addRegNr").click(function () {
$("#searchFields").append(str_to_append)
})
})
</script>
​
You can do it, using jquery append method.
here I leave a link with some examples:
http://api.jquery.com/append/
I guess, you might just be looking for something like this.
I would do something like this:
<div id="searchFields" class="control-group inlineForm">
<label for="regNr">Regnr </label><input type="text" id="regNr" class="uprCase" placeholder="Regnr." size="6" maxlength="6"/><br/>
</div>
<span class="addRegNr">add another</span><br/>
<label for="poNr">PO.nr</label> <input type="text" id="poNr" placeholder="PO.nr." size="12" maxlength="12">
<input type="button" value="GET INFO" class="last" id="getBaseInf">
and then some js that looked like this:
var $input = $("#searchFields").children();
$(".addRegNr").on("click", function(){
var $newField = $input.clone();
// change what you need to do with the field here.
$(this).siblings("#searchFields").append($newField);
});
It's also here: http://jsfiddle.net/tatLw/
Basing solution on this blog post jQuery – Dynamically Adding Form Elements by Charlie Griefer, you could try the following:
Markup:
<div id="searchFields" class="control-group inlineForm">
<form id="myForm">
<div id="input1" style="margin-bottom:4px;" class="clonedInput">
<label for="regNr">Regnr</label>: <input type="text" name="regNr" placeholder="Regnr." size="6" maxlength="6" />
<label for="poNr">PO.nr</label>: <input type="text" id="poNr" placeholder="PO.nr." size="12" maxlength="12">
</div>
<div>
<input type="button" id="btnAdd" value="add another Reg field" />
<input type="button" id="btnDel" value="remove fields" />
</div>
<input type="button" value="GET INFO" class="last" id="getBaseInf">
</form>
</div>​
Javascript:
$('#btnAdd').click(function() {
var num = $('.clonedInput').length; // how many "duplicatable" input fields we currently have
var newNum = new Number(num + 1); // the numeric ID of the new input field being added
// create the new element via clone(), and manipulate it's ID using newNum value
var newElem = $('#input' + num).clone().attr('id', 'input' + newNum);
// manipulate the name/id values of the input inside the new element
newElem.children(':first').attr('id', 'regNr' + newNum).attr('regNr', 'regNr' + newNum);
// insert the new element after the last "duplicatable" input field
$('#input' + num).after(newElem);
// enable the "remove" button
$('#btnDel').removeAttr('disabled');
// business rule: you can only add 5 names
if (newNum == 5)
$('#btnAdd').attr('disabled','disabled');
});
$('#btnDel').click(function() {
var num = $('.clonedInput').length;
$('#input' + num).remove(); // remove the last element
$('#btnAdd').attr('disabled',''); // enable the "add" button
// if only one element remains, disable the "remove" button
if (num-1 == 1)
$('#btnDel').attr('disabled','disabled');
});
$('#btnDel').attr('disabled','disabled');​
DEMO: http://jsfiddle.net/chridam/qW9ra/
To add any HTML with jQuery you will eventually end up calling .append(), or one of its variations like .before, .appendTo, etc.
These can be given raw HTML strings, but unless you have an HTML template ready and plain, don't use string concatenation to build your HTM. This is fragile and insecure. Instead, create the elements with jQuery() directly, like so:
jQuery('<input type="text"/>').attr({
value: '',
placeholder: '...',
id: '..'
})
.appendTo( .. )
In addition, don't forget to create labels for these new elements as well (if appropiate).
Another few best practices relevant to this scenario:
If you're going to be dynamically making new form elements appear (as opposed to adding more additional fields for an existing field), it is best to not create these with JavaScript. Instead make sure they are present in the page output from the beginning, then hide them from $(document).ready with .hide(). That way it will be a lot easier (as all you need is a reference to the hidden element, and call .show() when you have to). And that way it doesn't rely on javascript flow being present, enabled and functioning as expected because this way if anything happened along the way (exception thrown, cdn issues, whatever) the form will fallback to a fully-present version that just works.
If you're going to have a lot of these "+" or "add" button scenarios, I'd make a .clone() of the original field, strip it (clear value, remove id-attribute), and store it in a local variable. Then from the click handler, clone that, and put it into the document where you need it. You may also want to have a server-side fallback by making the add button a submit button with a certain name/value pair that the server detects as a non-final input in which case it will return the same page with the values pre-filled but with more fields.

Make input text fields changeable and selectable (toggled with checkbox)

Please see my current html snippet is as below. I am trying to make html input fields changeable and selectable. So I can change the value of colors in input text field which is toggled with the corresponding checkbox. When the submit button is clicked, only the information of the selected color is submitted.
My current html displays the content correctly, but it will submit two colors information. Despite of only one checkbox is selected.
<form id="myForm">
<input type="checkbox" name="color1" value="blue_check" />
Color1: <input type="text" name="blue" value="120" /></br>
<input type="checkbox" name="color2" value="red_check" />
Color2: <input type="text" name="red" value="160" /></br>
<input type="submit" value="OK" />
</form>
or click on: http://jsfiddle.net/4xDFK/56/
Thank you in advance.
With jQuery:
$(document).ready(function() {
$('#myForm :checkbox').each(function() {
$(this).next("input").attr('disabled',!$(this).is(':checked'));
});
});
$('#myForm :checkbox').change(function() {
$(this).next("input").attr('disabled',!$(this).is(':checked'));
});
As you don't mention the use of JavaScript or a JS-framework, here is a suggestion to solve it with the pure html form and server-side evaluation:
Give the checkboxes a telling name, like "check_blue" + "check_red"
On the server side, only process the color if the corresponding checkbox has been selected
If you only want to so submit or allow filling of the inputs according to the checkbox state, you have to use JavaScript (and should probably have mentioned that in your question or at least as a tag).
you can remove elements on submit , if related checkbox is not checked .
how to prevent form from sending some fields we don't want to send
All input values are submitted as you click hit the submit button. So what you need to do is to handle this on the server side. Give names to the checkboxes and check their values, google for "handling checkboxes in XXXX" where XXXX is your server side language.
<h1> Colors Information </h1>
<form id="myForm">
<input type="checkbox" name="choice1" value="choice1"/>
Color1: <input type="text" name="blue" value="120" /></br>
<input type="checkbox" name="choice2" value="choice2"/>
Color2: <input type="text" name="red" value="160" /></br>
<input type="submit" value="OK" />
</form>
You can then check which checkboxes are checked, and accordingly see if you should put the corresponding text input fields into consideration.

Categories

Resources