fill input if radio is selected using jquery - javascript

I have a input and two radio buttons.
The input accepts a number for a time period a person lives at a residence.
The radio buttons are months & years.
I want to fill a 2nd input using the 1st input value (numerical value of length at residence) and either the value for months or years based on the radio selected.
I've made it spit out the time, but it spits out the value for both radio button because I did not have an if statement to check. I already have jquery in my form and it works. I just need this small section of my form to work.
My question is, how do I set up the conditional statement for checking what radio is checked?
HTML
<input type="number" value="" required maxlength="5" class="form-control" name="homeLength" id="homeLength">
<input type="radio" id="years" value="Years" name="length" required> Years
<input type="radio" id="months" value="Months" name="length"> Months
jQuery
$('#months').click(function () {
if ($(this).attr("checked") == "checked") {
$('#homeLength, #months').bind('keypress blur', function () {
$('#homeTime').val($('#homeLength').val() + ' ' + ' ' + $('#months').val() + ' ' + ' ');
});
}
});
$('#years').click(function () {
if ($(this).attr("checked") == "checked") {
$('#homeLength, #years').bind('keypress blur', function () {
$('#homeTime').val($('#homeLength').val() + ' ' + ' ' + $('#years').val() + ' ');
});
}
});

You need to check the checked radio's value only and do that on keyup/blur AND click of any radio
$(function() {
$('#homeLength').on('keyup, blur', function() {
var lgt = $("input:radio[name=length]:checked").val();
$('#homeTime').val($(this).val() + ' '+lgt);
});
$("input:radio[name=length]").on("click",function() {
$('#homeLength').blur(); // trigger the blur event of the field to update
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<input type="number" value="" required maxlength="5" class="form-control" name="homeLength" id="homeLength">
<input type="radio" id="years" value="Years" name="length" required> Years
<input type="radio" id="months" value="Months" name="length"> Months
<hr/>
<input type="text" value="" class="form-control" name="homeTime" id="homeTime">

The most usable conditional statement for this kind of checkings is:
if ($(this).is(':checked'))
so as you can see the response is boolean.

Replave your javascript code with this
$('#months').click(function() {
console.log($(this).prop('id'));
$('#homeLength, #months').bind('keypress blur', function() {
$('#homeTime').val($('#homeLength').val() + ' ' + ' '+$('#months').val()+ ' ' + ' ');
});
});
$('#years').click(function() {
console.log($(this).prop('id'));
$('#homeLength, #years').bind('keypress blur', function() {
$('#homeTime').val($('#homeLength').val() + ' ' + ' ' + $('#years').val()+ ' ');
});
});
whenever user will select any radio button u can get its id by
$(this).prop('id');
its value by
$(this).prop('value');

Related

convert Checkbox into radio button using javascript?

I am trying to convert checkbox into radio button which is working partially , but not deselecting previous selected radio button.I am looking solution to show one button at a time as a selected.
var layers = {
'Esri_WorldImagery': Esri_WorldImagery.addTo(this.baseMap),
'World_Topo_Map': World_Topo_Map//.addTo(this.baseMap)
};
var layerHtml = '<ul class="fa-ul">';
for (var key in layers) {
if (layers.hasOwnProperty(key)) {
var state = this.baseMap.hasLayer(layers[key]) ? 'checked="checked"' : '';
//layerHtml += '<li><label><input type="checkbox" ' + state + ' value="' + key + '" >' + key + '</label>';
layerHtml += '<li><label><input type="radio" ' + state + ' value="' + key + '" >' + key + '</label>';
}
}
layerHtml += '</ul>';
var widget = $('<div id="layer-control" class="sidebar-widget">' + layerHtml + '</div>');
widget.on('click', 'input[type="radio"]', function (e) {
var was_Active = $(this).prop('checked');
var value = $(this).val();
if (was_Active) {
layers[value].addTo(self.baseMap);
}
else {
self.baseMap.removeLayer(layers[value]);
}
});
First, regarding the current code with radio elements, as #Aswin Ramesh has told you, yo should add the name attribute. From MDN:
A radio group is defined by giving each of radio buttons in the group the same name. Once a radio group is established, selecting any radio button in that group automatically deselects any currently-selected radio button in the same group.
Besides the shape (circle vs square) that's the only difference between the radio and checkbox elements. So consider that checkboxes that behave like radio buttons might be confusing for the user.
That said, if you really want to replicate that functionality on checkboxes, use JavaScript to deselect all the elements but the one which raised the click event.
$('#checkboxes').on('click', ':checkbox', function(e) {
$('#checkboxes :checkbox').each(function() {
if (this != e.target)
$(this).prop('checked', false);
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="radios">
<input type="radio" name="rOptions" value="radio1" checked>
<input type="radio" name="rOptions" value="radio2">
<input type="radio" name="rOptions" value="radio3">
</div>
<div id="checkboxes">
<input type="checkbox" value="checkbox1" checked>
<input type="checkbox" value="checkbox2">
<input type="checkbox" value="checkbox3">
</div>
Note: you forgot to close the <li> tags.

HTML Script capturing text and performing events with its own value

I'm trying to capture the value of 2 text inputs and performs functions when the user press enter key.
I'm using Internet Explorer 11.
<script type="text/javascript">
function myFuncion(arg1, arg2) {
window.alert("arg1:" + arg1 + ", arg2:" + arg2);
}
</script>
Now, the text inputs code
<input type="text" size="6" name="nameAnotherText" id="idAnotherText" value=""
onkeydown = "if (event.keyCode == 13) {
myFuncion('" + document.getElementById("idText").textContent + "', '"
+ document.getElementById('idAnotherText').value + "');
}"
/>
<input type="text" size="6" name="nameText" id="idText" value=""
onkeydown = "if (event.keyCode == 13) {
myFuncion('" + document.getElementById("idText").textContent + "', '"
+ document.getElementById('idAnotherText').value + "');
}"
/>
Is it not working.
Unfortunately this not works:
<button onclick="myFuncion('" +
document.getElementById(\"idAnotherText\").textContent + "', '" +
document.getElementById(\"idText\").textContent + "')" >Press Me</button>
<button onclick="myFuncion(" +
document.getElementById(\"idAnotherText\").textContent + ", " +
document.getElementById(\"idText\").textContent + ")" >Press Me</button>
<button onclick="myFuncion(" +
document.getElementById('idAnotherText').textContent + ", " +
document.getElementById('idText').textContent + ")" >Press Me</button>
How solve this?
Or something https://stackoverflow.com/a/155272/811293 but is not working:
Remove quotes from the function arguments. You also have to use value instead of textContent to grab the values from input fields in both cases. Try the following:
function myFuncion(arg1, arg2) {
window.alert("arg1:" + arg1 + ", arg2:" + arg2);
}
<input type="text" size="6" name="nameAnotherText" id="idAnotherText" value=""
onkeydown = "if (event.keyCode == 13) {
myFuncion(document.getElementById('idText').value, document.getElementById('idAnotherText').value);
}"
/>
<input type="text" size="6" name="nameText" id="idText" value=""
onkeydown = "if (event.keyCode == 13) {
myFuncion(document.getElementById('idText').value, document.getElementById('idAnotherText').value);
}"
/>
Writing JavaScript in HTML is not a good idea. You might do the following which is more cleaner:
function myFuncion(event) {
if (event.keyCode == 13) {
var txt1 = document.getElementById('idText').value;
var txt2 = document.getElementById('idAnotherText').value;
window.alert("txt1:" + txt1 + ", txt2:" + txt2);
}
}
<input type="text" size="6" name="nameAnotherText" id="idAnotherText" value="" onkeydown = "myFuncion(event);"/>
<input type="text" size="6" name="nameText" id="idText" value="" onkeydown = "myFuncion(event);"/>
If you are in a form with a submit button you need to return false from your event handler or your form will auto submit when return is pressed while in an input.
As a general rule you should avoid trying to handle Return presses in inputs in a form. This breaks the expected behavior of forms on the internet which is that they submit when return is pressed. Instead register a callback on the submit event of the form and do it (validations, ajax, etc.) there instead.
Rewriting the javascript makes it work. In general avoid putting actual code into the code
With this as the javascript
function myOnKeyDown(event) {
if (event.keyCode == 13) {
var text_value = document.getElementById("idText").value
var another_text_value = document.getElementById("idAnotherText").value
myFunction(text_value, another_text_value);
}
}
function myFunction(arg1, arg2) {
window.alert("arg1:" + arg1 + ", arg2:" + arg2);
}
You can have this in your html
<input type="text" size="6" name="nameAnotherText" id="idAnotherText" value="" onkeydown="myOnKeyDown(event)"/>
<input type="text" size="6" name="nameText" id="idText" value="" onkeydown="myOnKeyDown(event)"/>
This should allow your code to run.
I usually try to go as native as possible.
The way you can go about is to wrap the input fields with form tag and add event listener to the submit event.
Try the following.
const form = document.getElementById('myform');
form.addEventListener('submit', onSubmit, false);
form.submit = onSubmit;
function onSubmit(event) {
if (event) {
event.preventDefault();
}
console.log('submitted');
const input1 = document.getElementById('input1').value;
const input2 = document.getElementById('input2').value;
console.log({
input1,
input2
});
}
<form id="myform">
<input type="text" id="input1">
<input type="text" id="input2">
<button type="submit" style="display: none"></button>
</form>

Jquery , Html Append value to textfield when Checkbox is checked

I have a list of four check boxes which are as shown below :
<input type="checkbox" class="checkboxstyle" id="id_peer_educator" value="Peer Educator"/>Peer Educator<br>
<input type="checkbox" class="checkboxstyle" id="id_chw" value="CHW"/>CHW<br>
<input type="checkbox" class="checkboxstyle" id="id_health_provider" value="Health Prvider"/>Health Provider<br>
<input type="checkbox" class="checkboxstyle" id="id_purchase" value="Purchase"/>Purchase<br>
<input type="text" id="CD_Supplr" class="CD_Supplr" name="CD_Supplr" placeholder=" Suppliers : "/>
The first four are check boxes while the last one is a textbox. How can I append data to the text-field Suppliers ? (When it is checked , it should be appended to the text field Supplier, if it is unchecked, then the value should be removed from the text field supplier) .
I tried implementing it the following way :
var CD_Supplr = $('#CD_Supplr').val();
var id_peer_educator = $('#id_peer_educator').val();
var id_chw = $('#id_chw').val();
var id_health_provider = $('#id_health_provider').val();
var id_purchase = $('#id_purchase').val();
$('#id_peer_educator').click(function () {
$('#CD_Supplr').val(CD_Supplr + "," + id_peer_educator;
});
$('#id_chw').click(function () {
$('#CD_Supplr').val(CD_Supplr + "," + id_chw;
});
But it's not working,what's the best way to implement it?
You can use an array to add value when checkbox is checked and remove it when unchecked and use join() function to join the array values by dispay in input.
Hope this helps.
var selected_checkbox=[];
$('.checkboxstyle').change(function()
{
if($(this).is(':checked'))
{
//If checked add it to the array
selected_checkbox.push($(this).val());
}
else
{
//If unchecked remove it from array
for (var i=selected_checkbox.length-1; i>=0; i--)
{
if (selected_checkbox[i] === $(this).val())
selected_checkbox.splice(i, 1);
}
}
$('#CD_Supplr').val(selected_checkbox.join(','));
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input type="checkbox" class="checkboxstyle" id="id_peer_educator" value="Peer Educator"/>Peer Educator<br>
<input type="checkbox" class="checkboxstyle" id="id_chw" value="CHW"/>CHW<br>
<input type="checkbox" class="checkboxstyle" id="id_health_provider" value="Health Prvider"/>Health Provider<br>
<input type="checkbox" class="checkboxstyle" id="id_purchase" value="Purchase"/>Purchase<br>
<input type="text" id="CD_Supplr" class="CD_Supplr" name="CD_Supplr" size='50' placeholder=" Suppliers : "/>
Demo
$('.checkboxstyle').on("change",function ()
{
var str ="";
$('.checkboxstyle:checked').each(function()
{
str+= $(this).val()+" ";
});
$('#CD_Supplr').val(str);
});
Add listeners to the change event on the checkboxex, then using match() find out if the value of a checkbox is NOT already there in the CD_Suplr textbox. Then, use the result of this condition to add/remove the checkbox values:
var $target = $('#CD_Supplr');
$('[type="checkbox"]').change(function(){
if($target.val() == ''){
$target.val('Supplier: '); //default text
}
if(!$target.val().match($(this).val())){
var text = $target.val();
$target.val(text + ' ' + $(this).val() + ', ');
} else {
var text = $target.val();
$target.val(text.replace($(this).val()+', ', ''));
}
//make sure the last comma is removed
$target.val($target.val().replace(/\,$/, ''));
});
JSFiddle Demo.

radio btn selection will show select list or text field, then that value querys and displays in another text field

I have a form that when selecting the radio button it will query a database and populate either a select list or change select to a textbox for user input.(mostly working - won't go back to select after textbox - not as important now)
Then I want it to take the value from the select or textbox and put it in a string variable. Then I think I can take it from there. I hope. ( I will use string to query to get other info to populate bib numbers)
Here is my JS/php been trying everything
$(document).ready(function () {
var bibfield = "";
$('#a1').change(function () {
//$('#hiddenText').hide();
$('#hidden').empty();
//$('#hidden').show();
$.each(arrayShort, function (i, val) {
$('#hidden').append('<option value="' + val + '">' + val + '</option>');
});
});
$('#a2').change(function () {
//$('#hiddenText').hide();
$('#hidden').empty();
//$('#hidden').show();
$.each(arrayLong, function (i, val) {
$('#hidden').append('<option value="' + val + '">' + val + '</option>');
});
});
$('#a3').change(function () {
//$('#hidden').hide();
//$('#hiddenText')show();
$('#hidden').replaceWith('<input name="hidden" id="hiddenText" type="text" size="26" >');
});
})
here is my form
<input name="btn1" id="a1" type="radio" value="Radio button 1" />
<input name="btn1" id="a2" type="radio" value="Radio button 2" />
<input name="btn1" id="a3" type="radio" value="Radio button 3" />
<select id="hidden" name="hidden">
<option selected></option>
</select>
<input type="text" name="sBib" />
<input type="text" name="eBib" />
I need to populate the select if a1 or a2 is checked but if a3 is checked then I need to replace the select with a textbox BUT Then populate a variable bibfield so I can query with it.
New to this and I am so exhausted and can't think straight all help is appreciated!!!
here you are replacing hidden with hiddenText and again trying to find the hidden which is gone already
need to correct your code like below where i am replacing the whole select or input with same id="hidden"
$(document).ready(function () {
var bibfield = "";
// variable to indicate if select dropdown is available already otherwise create new
var selectAvailable=true;
$('#a1').change(function () {
//$('#hiddenText').hide();
//$('#hidden').empty();
//$('#hidden').show();
$.each(arrayShort, function (i, val) {
if(selectAvailable)
{
$('#hidden').append('<option value="' + val + '">' + val+ '</option>');
}
else
{
selectAvailable=true;
$('#hidden').replaceWith('<select id="hidden" name="hidden">
<option value="' + val + '">' + val + '</option></select>');
}
});
});
$('#a2').change(function () {
//$('#hiddenText').hide();
// $('#hidden').empty();
//$('#hidden').show();
$.each(arrayLong, function (i, val) {
if(selectAvailable)
{
$('#hidden').append('<option value="' + val + '">' + val + '</option>');
}
else
{
selectAvailable=true;
$('#hidden').replaceWith('<select id="hidden" name="hidden">
<option value="' + val + '">' + val + '</option></select>');
}
});
$('#a3').change(function () {
//$('#hidden').hide();
//$('#hiddenText')show();
selectAvailable=false;
$('#hidden').replaceWith('<input name="hidden" id="hidden" type="text" size="26" >');
});
});

jquery get all input from specific form

Is there any ways to populate all of the input from certain form?
let say, some thing like this:
<form id="unique00">
<input type="text" name="whatever" id="whatever" value="whatever" />
<div>
<input type="checkbox" name="whatever" id="whatever" value="whatever" />
</div>
<table><tr><td>
<input type="hidden" name="whatever" id="whatever" value="whatever" />
<input type="submit" value="qweqsac" />
</td></tr></table>
</form>
<form id="unique01">
<div>
<input type="text" name="whatever" id="whatever" value="whatever" />
<input type="checkbox" name="whatever" id="whatever" value="whatever" />
</div>
<table><tr><td>
<input type="hidden" name="whatever" id="whatever" value="whatever" />
</td></tr></table>
<select>blah...</select>
<input type="submit" value="qweqsac" />
</form>
etc forms... forms...
*note: each form might have a different amount of input and type and also different html structure
so is there any way to populate the input from certain form id? eg if i click submit button from certain form id, then jquery will populate for me all of the input within those form id.
currently what i'm doing is like this:
$("form").submit(function(){ return validateForm($(this)) });
function validateForm(form){
var retVal = true;
var re;
$.each(form.serializeArray(), function(i, field) {
var input = $('input[name='+field.name+']');
field.value = $.trim(field.value);
switch(field.name){
case "name" :
and another cases...
}
})
}
that was work,
but in that case, i only get the field.name and field.value, and actually what i want is, i want a jquery object for each input element, so i can access their css, id, name, and even animate those input element
is there any way for this?
please let me know and thank you in advance!
AnD
To iterate through all the inputs in a form you can do this:
$("form#formID :input").each(function(){
var input = $(this); // This is the jquery object of the input, do what you will
});
This uses the jquery :input selector to get ALL types of inputs, if you just want text you can do :
$("form#formID input[type=text]")//...
etc.
The below code helps to get the details of elements from the specific form with the form id,
$('#formId input, #formId select').each(
function(index){
var input = $(this);
alert('Type: ' + input.attr('type') + 'Name: ' + input.attr('name') + 'Value: ' + input.val());
}
);
The below code helps to get the details of elements from all the forms which are place in the loading page,
$('form input, form select').each(
function(index){
var input = $(this);
alert('Type: ' + input.attr('type') + 'Name: ' + input.attr('name') + 'Value: ' + input.val());
}
);
The below code helps to get the details of elements which are place in the loading page even when the element is not place inside the tag,
$('input, select').each(
function(index){
var input = $(this);
alert('Type: ' + input.attr('type') + 'Name: ' + input.attr('name') + 'Value: ' + input.val());
}
);
NOTE: We add the more element tag name what we need in the object list like as below,
Example: to get name of attribute "textarea",
$('input, select, textarea').each(
function(index){
var input = $(this);
alert('Type: ' + input.attr('type') + 'Name: ' + input.attr('name') + 'Value: ' + input.val());
}
);
Use HTML Form "elements" attribute:
$.each($("form").elements, function(){
console.log($(this));
});
Now it's not necessary to provide such names as "input, textarea, select ..." etc.
$(document).on("submit","form",function(e){
//e.preventDefault();
$form = $(this);
$i = 0;
$("form input[required],form select[required]").each(function(){
if ($(this).val().trim() == ''){
$(this).css('border-color', 'red');
$i++;
}else{
$(this).css('border-color', '');
}
})
if($i != 0) e.preventDefault();
});
$(document).on("change","input[required]",function(e){
if ($(this).val().trim() == '')
$(this).css('border-color', 'red');
else
$(this).css('border-color', '');
});
$(document).on("change","select[required]",function(e){
if ($(this).val().trim() == '')
$(this).css('border-color', 'red');
else
$(this).css('border-color', '');
});

Categories

Resources