remove disabled attribute according input value - javascript

function add_option(){
var tot_option=parseInt($('#tot_option').val());
tot_option++;
$('#tot_option').val(tot_option);
var par="'radio"+tot_option+"'";
var opt="<input type='text' id='opt"+tot_option+"' onblur='chk(this.value,'"+par+"')' name='answers[]' style='width:80%;' onfocus='add_option()'> <input type='radio' id='radio"+tot_option+"' required disabled name='canswer' value='"+tot_option+"'><br><br>";
document.querySelectorAll("input[onfocus]").forEach(function(element, index) {
element.removeAttribute("onfocus");
});
$('#new_option').append(opt);
}
function chk(ivalue,rad){
if(ivalue!=''){
$('#'+rad).removeAttr('disabled');
}else{
$('#'+rad).attr('disabled','disabled');
$('#'+rad).removeAttr('checked','checked');
}
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<input type="text" style='width:80%;' onblur="chk(this.value,'radio1')" id="opt1" name="answers[]">
<input type="radio" id="radio1" disabled required name="canswer" value="1"><br><br>
<input type="text" id="opt2" onblur="chk(this.value,'radio2')" style='width:80%;' name="answers[]" onfocus="add_option()">
<input type="radio" id="radio2" required disabled name="canswer" value="2"><br><br>
<span id="new_option"></span>
i have multiple input type and one radio button in front of every input i want to remove disabled from radio if my input type have some value if it has no value then add disabled attribute to radio. its working fine in first two input but after that its not working

there were some flaws in your code,
1 you are sending this.value here as a string onblur='chk(this.value,'"+par+"')
2 in this onblur function call there is a problem while sending par as a parameter,
so here I Modified your code a bit and now this is working
function add_option(){
var tot_option=parseInt($('.totalOption').length);
tot_option++;
$('#tot_option').val(tot_option);
var par="'radio"+tot_option+"'";
var onBlur = 'onblur=chk('+ par.toString() +')';
var opt="<input type='text' id='opt"+tot_option+"' class='totalOption' " + onBlur + " name='answers[]' style='width:80%;' onfocus='add_option()'> <input type='radio' id='radio"+tot_option+"' required disabled name='canswer' value='"+tot_option+"'><br><br>";
document.querySelectorAll("input[onfocus]").forEach(function(element, index) {
element.removeAttribute("onfocus");
});
$('#new_option').append(opt);
}
function chk(rad){
if(event.relatedTarget == null)
return;
var SelctedTarget = Number(event.relatedTarget.id[event.relatedTarget.id.length - 1]) - 1;
var ivalue = $('#opt' + SelctedTarget).val();
if(ivalue!=''){
$('#'+rad).removeAttr('disabled');
}else{
$('#'+rad).attr('disabled','disabled');
$('#'+rad).removeAttr('checked','checked');
}
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<input type="text" style='width:80%;' onblur="chk('radio1')" id="opt1" class="totalOption" name="answers[]">
<input type="radio" id="radio1" disabled required name="canswer" value="1"><br><br>
<input type="text" id="opt2" class="totalOption" onblur="chk('radio2')" style='width:80%;' name="answers[]" onfocus="add_option()">
<input type="radio" id="radio2" required disabled name="canswer" value="2"><br><br>
<span id="new_option"></span>

Related

How to get all checkbox values and put value of each one to a specific text input

I have a checkbox with (20) choices and also (20) input fields , i need : when user choose one or more option, put value of checked checkbox in a separate input field else put (0)
I tried the following and it working when user chose only one option.
$(".cont").change(function() {
if($('.cont :checked').val() == "1") {
$('#q1').val('1');
}else{
$('#q1').val('0');
}
if($('.cont :checked').val() == "2") {
$('#q2').val('2');
}else{
$('#q2').val('0');
}
if($('.cont :checked').val() == "3") {
$('#q1').val('3');
}else{
$('#q3').val('0');
}
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="cont">
<input type="checkbox" value="1">
<input type="checkbox" value="2">
<input type="checkbox" value="3">
</div>
<input id="q1" type="text" >
<input id="q2" type="text" >
<input id="q3" type="text" >
You can combine the uses of .val() and .is(':checked').
$('#q' + $(this).val()) will select the correct text input.
$(this).is(':checked') ? $(this).val() : 0 will put your checkbox value inside your input if checked, 0 if not.
$('.cont input[type="checkbox"]').change(function() {
$('#q' + $(this).val()).val($(this).is(':checked') ? $(this).val() : 0);
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="cont">
<input type="checkbox" value="1">
<input type="checkbox" value="2">
<input type="checkbox" value="3">
</div>
<input id="q1" type="text">
<input id="q2" type="text">
<input id="q3" type="text">
You need to follow these steps and use much more managed code to achieve this:
Detect change on checkbox checked/unchecked
Get the value of the checkbox and since the id of the input element
is prefixed with q and the value of the checkbox, get the id
first
Use this id to fill the value in the input element.
In addition, you can check for uncheck of the checkbox and substitute
the previous value with null.
$('input[type="checkbox"]').change(function() {
var checkedValue = $(this).val();
var inputElemId = "q"+checkedValue;
if($(this).is(':checked')){
$('#'+inputElemId).val(checkedValue);
} else {
$('#'+inputElemId).val(null);
}
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="cont">
<input type="checkbox" value="1">
<input type="checkbox" value="2">
<input type="checkbox" value="3">
</div>
<input id="q1" type="text" >
<input id="q2" type="text" >
<input id="q3" type="text" >

jQuery & JavaScript Excercise: Adding Values On Condition

How do you make it calculate using JavaScript/jQuery based on condition:
on radio button 'change' event.
if user clicks "Yes" or "N/A", the value of text boxes with default values next to it will be added and reflected in Total
HTML:
<form>
<fieldset>
<input type="radio" name="remark[]" value="Yes" class="answer">Yes
<input type="radio" name="remark[]" value="No" class="answer">No
<input type="radio" name="remark[]" class="answer">N/A
<input type="text" name="point1" class="score" value="3">
</fieldset>
<fieldset>
<input type="radio" name="remark[]" value="Yes" class="answer">Yes
<input type="radio" name="remark[]" value="No" class="answer">No
<input type="radio" name="remark[]" class="answer">N/A
<input type="text" name="point2" class="score" value="2">
</fieldset>
Total<input type="text" name="total" class="result">
</form>
Vanilla Javascript
Note: these scripts associate with forms that have the class name calc
This script will associate with the form, so if you have multiple instances each form will calculate separately.
Basically for each form select all input's with a value of 'Yes' which are checked, then find the score for that field set and add it to the total
(Demo)
(function(){
"use strict";
function calculate() {
var forms = document.querySelectorAll('.calc'), form, i;
for (i = 0; form = forms[i]; i++) {
var total = 0;
var inputs = form.querySelectorAll('input[value="Yes"]:checked'), input, x;
for (x = 0; input = inputs[x]; x++) {
total += parseFloat(input.parentElement.lastElementChild.value);
}
form.lastElementChild.value = total;
}
}
calculate();
var inputs = document.querySelectorAll('.calc input'), input, x;
for(x = 0; input = inputs[x]; x++) {
input.onchange = calculate;
}
})();
jQuery
If you would like to use jQuery, this is the same script converted to jQuery
(Demo)
(function(){
"use strict";
function calculate() {
$('.calc').each(function(){
var total = 0;
$('input[value="Yes"]:checked', this).each(function(){
total += parseFloat($('input.score', this.parentElement).val());
});
$('input.result', this).val(total);
});
}
calculate();
$('.calc input').on('change', calculate);
})();
Not sure if I understand correctly, but first you'll need a few changes in your markup, radio groups should have different name so it'll be like remark[0] for first group and remark[1] for the second and so on. The "N/A" radios don't seem to have a value so I've added value="NA" to them. So your HTML will look like:
<form>
<fieldset>
<input type="radio" name="remark[0]" value="Yes" class="answer" />Yes
<input type="radio" name="remark[0]" value="No" class="answer" />No
<input type="radio" name="remark[0]" value="NA" class="answer" />N/A
<input type="text" name="point1" class="score" value="3" />
</fieldset>
<fieldset>
<input type="radio" name="remark[1]" value="Yes" class="answer" />Yes
<input type="radio" name="remark[1]" value="No" class="answer" />No
<input type="radio" name="remark[1]" value="NA" class="answer" />N/A
<input type="text" name="point2" class="score" value="2" />
</fieldset>Total
<input type="text" name="total" class="result" />
</form>
Then we just listen to radio's onchange and if Yes or N/A is selected for each group, we have it's value to the total. I used parseInt on values since they're string and it seemed the values were supposed to work as numbers. (2+3 should be 5 and not 23).
$('form input[type=radio]').on('change', function() {
var total = 0;
$('form fieldset').each(function(i) {
var point = parseInt($(this).find('input[type=text]').val());
var val = $(this).children('[name="remark[' + i + ']"]:checked').val();
if(val == "Yes" || val == "NA")
total += point;
});
$('input[name="total"]').val(total);
});
jsfiddle DEMO

Any way to change a list of radio buttons to a select drop down dynamically?

I'm trying to find a work around to a dynamically created form that for whatever reason doesn't give the option of a select list, only radio and check inputs. There is no way for me to go in and change the code so I was curious if there is a way to transform a list of radio buttons to a select drop down using jquery?
for example, if I have this code:
<form>
<div class="col-lg-5">
<p class="bullet"><b><font class="required" size="3" color="FF0000">* </font></b></p>
<p class="inputLabel">First Name:</p>
<input type="text" size="25" name="Text1" value="">
</div>
<div class="col-lg-5">
<input type="radio" name="gender" value="male">Male<br>
<input type="radio" name="gender" value="female">Female
</div>
<div class="col-lg-10"><p>Current Employer / Facility:</p>
<input type="text" size="25" name="Text9" value="">
</div>
</form>
is there anyway to change it to:
<form>
<div class="col-lg-5">
<p class="bullet"><b><font class="required" size="3" color="FF0000">* </font></b></p>
<p class="inputLabel">First Name:</p>
<input type="text" size="25" name="Text1" value="">
</div>
<select name="gender">
<option value ="male">Male</option>
<option value ="female">Female</option>
</select>
<div class="col-lg-10"><p>Current Employer / Facility:</p>
<input type="text" size="25" name="Text9" value="">
</div>
</form>
Here's one way:
var sel = $('<select name="gender">').append(function () {
var opts='';
$('input[name="gender"]').each(function () {
opts += '<option value ="' + this.value + '">' + this.value.charAt(0).toUpperCase() + this.value.slice(1) + '</option>';
})
return opts;
});
$('form div.col-lg-5:eq(1)').empty().append(sel);
jsFiddle example
var select = $("<select></select>").attr("name", "gender");
$('form input[name="gender"]').each(function(index, item) {
$('<option/>', {
'value': this.value,
'text': this.value
}).appendTo(select);
});
This JSFiddle is as close as I was able to get it.
HTML:
<form>
<input type="radio" name="gender" value="male">Male<br>
<input type="radio" name="gender" value="female">Female
</form>
Javascript:
var select = $('form').append($('<select>', {
name: 'gender',
id: 'genderSelect'
}));
$("form > input[type='radio']").each(function() {
$('#genderSelect').append($('<option>', {
value: $(this).val(),
text: $(this).val()
}));
$(this).remove();
});
You'll need to do something with the labels for the radio buttons to grab the values or get rid of them more easily.

How to add onChange function for all HTML form fields

My HTML Page has 10 Text Fields.
Currently no onChange EVENT is available for all ten fields.
<input type="text" name="text1" value="1">
<input type="text" name="text2" value="2">
<input type="text" name="text3" value="3">
<input type="text" name="text4" value="">
<input type="text" name="text5" value="">
<input type="text" name="text6" value="">...
Now, I want to add onChange Function in all fields whose field is of input type.
How do I add onChange or onBlur even in my JS section?
In onChange function, I will call ajax function which will validate whether the field has Hacking Keywords.
So my question is:
How do I add onChange function for all form fields. My field should dynamically be like below:
<input type="text" name="text1" value="1" onChange="javascript:fnName" onBlur="javascript:fnName" >
<input type="text" name="text2" value="2" onChange="javascript:fnName" onBlur="javascript:fnName" >
<input type="text" name="text3" value="3" onChange="javascript:fnName" onBlur="javascript:fnName" >
<input type="text" name="text4" value="" onChange="javascript:fnName" onBlur="javascript:fnName" >
<input type="text" name="text5" value="" onChange="javascript:fnName" onBlur="javascript:fnName" >
<input type="text" name="text6" value="" onChange="javascript:fnName" onBlur="javascript:fnName" >
<input type="text" name="text7" value="" onChange="javascript:fnName" onBlur="javascript:fnName" >
This can be achieved with vanilla JavaScript as zvona suggests.
Here is a simple loop to mock an HTML5 placeholder. <<DEMO>>
var prompt = 'Type something here';
var textFields = document.querySelectorAll('input[name^="text"]');
var index = 0;
for (index = 0; index < textFields.length; ++index) {
var textField = textFields[index];
textField.addEventListener('change', onChangeHandler);
textField.addEventListener('focus', onFocusHandler);
textField.addEventListener('blur', onBlurHandler);
textField.value = prompt;
console.log(textField);
}
function onChangeHandler() {
// Do something...
}
function onFocusHandler() {
if (this.value === prompt) {
this.value = '';
}
}
function onBlurHandler() {
if (this.value === '') {
this.value = prompt;
}
}
you can try to give change function to your form using
$('.form :input').change(function(e){
$('#log').prepend('<p>Form changed ' + $(e.target).attr('id') + '</p>')
});
Demo1
Demo2
[].forEach.call(document.querySelectorAll("input"), function(input) {
input.addEventListener("change", fnName, false);
input.addEventListener("blur", fnName, false);
});
getElementsByTagname() gets you an array of all input. Interate over them and addEventListener.
Or use jQuery's $('input').on('change'...)
Try something like:
var inputList = document.getElementsByTagName("input");
for(var i=0;i<inputList.length;i++){
inputList[i].onchange = function(){
//function here
}
inputList[i].onblur = function(){
//function here
}
}

jquery: how to check if all radio buttons in a div are selected

my html looks like this
<div id="div1">
<input type="radio" name="r1" value="v1" />
<input type="radio" name="r1" value="v2" />
<input type="radio" name="r1" value="v3" />
<input type="radio" name="r2" value="v1" />
<input type="radio" name="r2" value="v2" />
<input type="radio" name="r2" value="v3" />
<input type="radio" name="r3" value="v1" />
<input type="radio" name="r3" value="v2" />
<input type="radio" name="r3" value="v3" />
</div>
radio buttons are dynamically generated on my html so in that div i don't know how many radio buttons i have.
i want to make sure that the user will select a value for each one of them before he submits the form, how can i check that all radio buttons inside my div has a value checked?
Thank you
$(":radio").change(function() {
var names = {};
$(':radio').each(function() {
names[$(this).attr('name')] = true;
});
var count = 0;
$.each(names, function() {
count++;
});
if ($(':radio:checked').length === count) {
alert("all answered");
}
}).change();
Demo: http://jsfiddle.net/yFaAj/15/
Restructure your HTML slightly - wrap each radio group in (say) a div. Then you can just do something like this to validate the form when the user submits it:
if ($('div:not(:has(:radio:checked))').length) {
alert("At least one group is blank");
}
Of course this can be tweaked in various ways to suit your HTML. The idea was from Find all radio groups which haven't been selected
Solution here http://jsfiddle.net/QxdnZ/1/
var checked = $("#div1 :radio:checked");
var groups = [];
$("#div1 :radio").each(function() {
if (groups.indexOf(this.name) < 0) {
groups.push(this.name);
}
});
if (groups.length == checked.length) {
alert('all are checked!');
}
else {
var total = groups.length - checked.length;
var a = total>1?' groups are ':' group is ';
alert(total + a + 'not selected');
}
Validate the form when the user submits it, using this validation code.
var blank = false;
$("input:radio").each(function() {
var val = $('input:radio[name=' + this.name + ']:checked').val();
if (val === undefined) {
blank = true;
return false;
}
});
alert(blank ? "At least one group is blank" : "All groups are checked");
First we get the names of all the radio button groups, then check that each one has a value. (Actually we're doing multiple checks, but that doesn't really matter.)
Looking for something along these lines? http://jsfiddle.net/gXsZp/3/
<div id="div1">
Q1
<input type="radio" name="r1" value="v1" />
<input type="radio" name="r1" value="v2" />
<input type="radio" name="r1" value="v3" />
<br/>Q2
<input type="radio" name="r2" value="v1" />
<input type="radio" name="r2" value="v2" />
<input type="radio" name="r2" value="v3" />
<br/>Q3
<input type="radio" name="r3" value="v1" />
<input type="radio" name="r3" value="v2" />
<input type="radio" name="r3" value="v3" />
</div>
<br/>
<input id="btn" type="submit" text="submit"/>
$('#btn').click(function(){
if ( $('#div1 input:radio:checked').size() == 3 )
return true;
return false;
});
Try this one:
$('input:radio', $('#div1')).each(function() {
if(name && name == $(this).attr('name'))
return true; // Skip when checking the same element name.
name = $(this).attr('name');
if(! $('input:radio[name="' + name + '"]:checked').length) {
alert('Oops, you missed some input there.. [' + name + ']');
return false;
}
});
It will loop through every radio button to check for checked radio & will break as soon it found non-checked radio group (first error found). But if you prefer to get all the errors (not only the first error found), just remove return false.
Try this:
function check(){
var allCheck = true;
if($("#div1 :radio:checked").length==0){
allCheck=false;
}
$("#div1 :radio").each(function(){
for(var i=0;i<$("#div1 :radio:checked").length;i++)
if($(this).attr("name")===$($("#div1 :radio:checked")[i]).attr("name"))
break;
else if(i==$("#div1 :radio:checked").length-1)
allCheck = false;
});
return allCheck;
}
This will work:
if($("#div1").children("input:radio:checked").size() == 3)
{
alert('three inputs were checked');
}

Categories

Resources