How to access the value of checked radio box through javascript - javascript

I am rendering a HTML form through JS and when the user fills the data and clicks on submit, then I am converting into a JSON. But I am unable to fetch the value of checked radio box. Here's my code for rendering the radio box-
return '<div class="">\
<label class="" for="">Gender</label>\
<div class="">\
<div id="">\
<div class="">\
<label for="" class="radio">Male</label>\
<input id="" type="radio" name = "gender" value="M">\
</div>\
<div class="">\
<label for="" class="radio">Female</label>\
<input id="" type="radio" name = "gender" value="F">\
</div>\
<div class="">\
<label for="" class="radio">Others</label>\
<input id="" type="radio" name = "gender" value="O">\
</div>\
</div>\
</div>\
</div>';
};
Here's my function to convert user filled form to JSON,
var convertIntoJSON = function(elements) {
return [].reduce.call(elements, function(data, element){
data[element.name] = element.value;
return data;
}, {});
};
I am calling the above function, as convertIntoJSON(form.elements), where form is my actual form container.
Please tell me how can I access the checked radio button through this, through this code no matter what I select in gender field, I am getting gender as "O" everytime.

As I said in my comment, you can't use this shorthand to get the value of a radio array. Here's a workaround that still supports your original function for non-radio inputs:
var convertIntoJSON = function(elements) {
return [].reduce.call(elements, function(data, element){
if (element.type === "radio") {
if (element.checked) {
data[element.name] = element.value;
}
} else {
data[element.name] = element.value;
}
return data;
}, {});
};
var logSelected = document.getElementById('logSelected');
var form = document.getElementById('theForm');
logSelected.addEventListener('click',() => {
console.log(convertIntoJSON(form.elements));
})
<form id="theForm">
<label for="" class="radio">Male</label>
<input id="" type="radio" name = "gender" value="M">
<label for="" class="radio">Female</label>
<input id="" type="radio" name = "gender" value="F">
<label for="" class="radio">Others</label>
<input id="" type="radio" name = "gender" value="O">
</form>
<input type="button" value="log selected" id="logSelected"/>

Related

How capture the input radio value in javascript?

For example I have the next options in html, define the global name and different id to each input radio:
<form id="mokepon-form">
<input type="radio" name="mokepon" id="hipodoge">
<label for="hipodoge">Hipodoge</label>
<input type="radio" name="mokepon" id="capipego">
<label for="capipego">Capipego</label>
<input type="radio" name="mokepon" id="ratigueya">
<label for="ratigueya">Ratigueya</label>
<button type="submit">Seleccionar</button>
</form>
To read the value I read the selector, the global name and the checked attribute and then read the id property, you can use the value property as well.
const chooseMokepon = (e) => {
e.preventDefault();
const $selectedMokepon = document.querySelector('input[name=mokepon]:checked');
const { id: mokeponValue } = $selectedMokepon;
if (!mokeponValue) return;
console.log(mokeponValue);
}
$mokeponForm.addEventListener('submit', e => chooseMokepon(e));
You might use this snippet:
let submitBtn = document.querySelector('button[type="submit"]');
submitBtn.addEventListener('click', function(event){
event.preventDefault();
let selectedOption = document.querySelector('input[type="radio"][name="mokepon"]:checked');
if(selectedOption && selectedOption.value){
console.log('Selected: ' + selectedOption.value);
}
});
<form id="mokepon-form">
<input type="radio" name="mokepon" id="hipodoge" value="hipodoge">
<label for="hipodoge">Hipodoge</label>
<input type="radio" name="mokepon" id="capipego" value="capipego">
<label for="capipego">Capipego</label>
<input type="radio" name="mokepon" id="ratigueya" value="ratigueya">
<label for="ratigueya">Ratigueya</label>
<button type="submit">Seleccionar</button>
</form>

Link Radiobox button to Input

I have 2 radio button, each valued Yes and No respectively and 1 textbox.. If I checked on No button, the input textbox will open. If checked on Yes, textbox will disabled.
This code is working fine but I want to delete content that input to the textbox if the user checked Yes
function ismcstopu() {
var chkNo = document.getElementById("radio2_ismcstop");
var mcnostopreason = document.getElementById("mcnostopreason");
mcnostopreason.disabled = chkNo.checked ? false : true;
if (!mcnostopreason.disabled) {
mcnostopreason.focus();
} else {
mcnostopreason.val('');
}
}
<input type="radio" class="form-check-input" id="radio1_ismcstop" name="ismcstop" onclick="ismcstopu()" value="Yes">Yes
<input type="radio" class="form-check-input" id="radio2_ismcstop" name="ismcstop" onclick="ismcstopu()" value="No">No
<label for="mcnostopreason">If No, Reason:</label>
<input class="inputstyle-100" type="text" id="mcnostopreason" name="mcnostopreason" value="" disabled>
.val is a jQuery construct but you are using DOM
Here is a better version using eventListener
Change the document.getElementById("container") to whatever container you have (your form for example)
Note: It is often better to test true than to test false
I also added labels to the radios so we can click the yes or no too
document.getElementById("container").addEventListener("click", function(e) {
const tgt = e.target;
if (tgt.name === "ismcstop") {
const mcnostopreason = document.getElementById("mcnostopreason");
mcnostopreason.disabled = tgt.value === "Yes";
if (mcnostopreason.disabled) {
mcnostopreason.value = '';
} else {
mcnostopreason.focus();
}
}
})
<div id="container">
<label><input type="radio" class="form-check-input" id="radio1_ismcstop" name="ismcstop" value="Yes">Yes</label>
<label><input type="radio" class="form-check-input" id="radio2_ismcstop" name="ismcstop" value="No">No</label>
<label for="mcnostopreason">If No, Reason:
<input class="inputstyle-100" type="text" id="mcnostopreason" name="mcnostopreason" value="" disabled>
</label>
</div>
jQuery version
$("[name=ismcstop]").on("click", function() {
if (this.name === "ismcstop") {
const $mcnostopreason = $("#mcnostopreason");
$mcnostopreason.prop("disabled", this.value === "Yes");
if ($mcnostopreason.is(":disabled")) {
$mcnostopreason.val("");
} else {
$mcnostopreason.focus();
}
}
})
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<label><input type="radio" class="form-check-input" id="radio1_ismcstop" name="ismcstop" value="Yes">Yes</label>
<label><input type="radio" class="form-check-input" id="radio2_ismcstop" name="ismcstop" value="No">No</label>
<label for="mcnostopreason">If No, Reason:
<input class="inputstyle-100" type="text" id="mcnostopreason" name="mcnostopreason" value="" disabled>
</label>
mcnostopreason is not a jQuery object. therefore you could do: var mcnostopreason = $("#mcnostopreason");
Or you could just change mcnostopreason.val('') to mcnostopreason.value = '' ( this will mean you don't need to change anything else)

Adding values to placeholder using checkbox

Basically I have 4 checkbox elements in my form and a text field up top. The text field has a placeholder with a product name — product price format. Each checkbox has a product name and product price as well, and I want to use javascript to change the placeholder value once a checkbox is checked. The issue is that the product price should be a SUM of default placeholder base price and the product price of the checkbox that was checked. The first part of the placeholder should change from product name to product name + product name.
So far I have only been able to use javascript to change the value of the placeholder entirely, which would work if I had only one checkbox, but I have 4 so it doesn't.
In a perfect world the placeholder should display Basic Package + Video + Picture + Tour + Emergency — €30 when all checkboxes are checked, and Basic Package + Picture + Tour — €20 when only Option2 and Option3 are checked. And so on, and so on.
Here is a simplified code of what I am trying to achieve (note: only Video works in my code):
$('.Option1').on('change', function(e) {
if ($(this).is(':checked') === true) {
$('.PriceInput').attr('placeholder', 'Basic Package + Video — €15');
} else $('.PriceInput').attr('placeholder', 'Basic Package — €10');
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<form id="ajax-contact-basic" method="post" action="mailer-basic.php">
<div class="field">
<input class="form-control PriceInput" type="text" name="basicpackage" id="basicpackage" placeholder="Basic Package — €10" disabled />
</div>
<div class="field">
<input class="Option1" type="checkbox" id="videobasic" name="optiesbasic[]" value="Video">
<label for="videobasic">Video — €5</label>
</div>
<div class="field">
<input class="Option2" type="checkbox" id="picturebasic" name="optiesbasic[]" value="Picture">
<label for="picturebasic">Picture — €5</label>
</div>
<div class="field">
<input class="Option3" type="checkbox" id="tourbasic" name="optiesbasic[]" value="Tour">
<label for="tourbasic">Tour — €5</label>
</div>
<div class="field">
<input class="Option4" type="checkbox" id="emergencybasic" name="optiesbasic[]" value="Emergency">
<label for="emergencybasic">Emergency — €5</label>
</div>
I've removed the number from each class="Option"
then you can do something like this:
$('.Option').on('change', function(e) {
var s = "";
var p = 10;
$('.Option').each(function() {
if ($(this).is(':checked') === true) {
s += " + " + $(this).val();
var tempP = +$(this).next().text().split('€')[1];
p = p + tempP;
}
});
$('.PriceInput').attr('placeholder', 'Basic Package' + s + ' — €' + p);
});
Demo
$('.Option').on('change', function(e) {
var s = "";
var p = 10;
$('.Option').each(function() {
if ($(this).is(':checked') === true) {
s += " + " + $(this).val();
var tempP = +$(this).next().text().split('€')[1];
p = p + tempP;
}
});
$('.PriceInput').attr('placeholder', 'Basic Package' + s + ' — €' + p);
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<form id="ajax-contact-basic" method="post" action="mailer-basic.php">
<div class="field">
<input class="form-control PriceInput" type="text" name="basicpackage" id="basicpackage" placeholder="Basic Package — €10" disabled />
</div>
<div class="field">
<input class="Option" type="checkbox" id="videobasic" name="optiesbasic[]" value="Video">
<label for="videobasic">Video — €5</label>
</div>
<div class="field">
<input class="Option" type="checkbox" id="picturebasic" name="optiesbasic[]" value="Picture">
<label for="picturebasic">Picture — €5</label>
</div>
<div class="field">
<input class="Option" type="checkbox" id="tourbasic" name="optiesbasic[]" value="Tour">
<label for="tourbasic">Tour — €5</label>
</div>
<div class="field">
<input class="Option" type="checkbox" id="emergencybasic" name="optiesbasic[]" value="Emergency">
<label for="emergencybasic">Emergency — €5</label>
</div>

How to set radio buttons values based on dropdown selection?

I want to set radio buttons values based on drop-down selection,Lets assume i have three values in drop-down(A,B and C) , If A or B is selected i want to set radio button default value to Summary and if C is selected i want set value to Detailed. Also when A & B is selected i want to make it non-editable..
Please help this is first time i am using radios with AngularJS.
main.html
<div class="row">
<div class="form-group col-md-6 fieldHeight">
<label for="cycleName" class="col-md-6 required">Scope Type :</label>
<div class="col-md-6">
<select kendo-drop-down-list k-data-text-field="'text'"
k-option-label="'Select'" k-data-value-field="'id'"
k-data-source="assessmentTypeOptions" name="assessmentType"
required ng-model="riskAssessmentDTO.scopeType" id="assessmentType"
maxlength="256" ng-change="assessmentType()"></select>
<p class="text-danger"
ng-show="addAssessment.assessmentType.$touched && addAssessment.assessmentType.$error.required">Assessment
Type is required</p>
</div>
</div>
<div class="form-group col-md-6 fieldHeight">
<label for="assessmentType" class="col-md-5 required">Assessment Type :</label>
<label class="radio-inline"><input type="radio"
name="summary" id="summary" ng-value="'summary'"
ng-model="riskAssessmentDTO.erhFlag" ng-disabled="disableAssessmentType" >Summary </label>
<label class="radio-inline"><input type="radio"
name="detail" id="detail" ng-value="'N'"
ng-model="riskAssessmentDTO.erhFlag" ng-disabled="disableAssessmentType">Detailed</label>
<p class="text-danger"
ng-show="addAssessment.includeERHFlag.$touched && addAssessment.includeERHFlag.$error.required">Assessment
Name is required</p>
</div>
</div>
main.js
$scope.assessmentType = function() {
$scope.riskAssessmentDTO.assessmentName = '';
$scope.riskAssessmentDTO.erhFlag = 'Y';
$scope.showRefineERH = false;
if ($scope.riskAssessmentDTO.scopeType === 'RA_GEO_LOCAT') {
$scope.disableAssessmentType = true;
$scope.riskAssessmentDTO.erhFlag = 'summary';
} else if ($scope.riskAssessmentDTO.scopeType === 'RA_LEGAL_ENTITY') {
$scope.disableAssessmentType = true;
$scope.riskAssessmentDTO.erhFlag = 'summary';
} else if ($scope.riskAssessmentDTO.scopeType === 'RA_BUS_UNIT') {
$scope.disableAssessmentType = false;
$scope.riskAssessmentDTO.erhFlag = 'detailed';
}
};
Use ng-disabled in Radio buttons and use a scope variable as $scope.selectedIndex to set it as false or true
<input type="radio" ng-disabled="selectedInderx==0">
and set $scope.selectedIndex in the ng-change function in Select by passing $index from html

Pass array of checkboxes with ajax along with other inputs

Currently I have been using ajax to post to a few methods in my code igniter installation. I now have a form that has a checkbox array with other inputs and am having problems passing the value into post. Currently it returns the last value of the the last checkbox even if it's not checked.
.js
$('.flagPost').on('submit', function() {
var that = $(this), url = that.attr('action'), type = that.attr('method'), data = {};
that.find('[name]').each(function(index, value) {
var that = $(this), name = that.attr('name'), value = that.val();
data[name] = value;
});
$.ajax({
url : url,
type : type,
data : data,
success : function(response) {
$('#flagSuccess').empty().append(response).fadeIn('slow').delay(3000).fadeOut(800);
}
});
return false;
});
.html
<div class="form-group">
<label for="email" class="col-sm-4 control-label">Email</label>
<div class="col-sm-8">
<input type="email" class="form-control input-sm" name="email" id="email" placeholder="Email Address" value="<?php echo set_value('email');?>">
</div>
<span class="help-block"></span>
</div>
<div class="form-group">
<label class="control-label col-sm-4">Issues/Problems</label>
<div class="col-sm-8">
<label class="checkbox" for="problems-0">
<input type="checkbox" name="problem[]" id="problems-0" value="Adult Content">
Adult Content
</label>
<label class="checkbox" for="problems-1">
<input type="checkbox" name="problem[]" id="problems-1" value="Spam">
Spam
</label>
<label class="checkbox" for="problems-2">
<input type="checkbox" name="problem[]" id="problems-2" value="Non-existent">
Non-existent
</label>
<label class="checkbox" for="problems-3">
<input type="checkbox" name="problem[]" id="problems-3" value="Language">
Language
</label>
<label class="checkbox" for="problems-4">
<input type="checkbox" name="problem[]" id="problems-4" value="Other">
Other
</label>
</div>
<span class="help-block"></span>
</div>
<!-- Textarea -->
jQuery has a serialize method for grabbing all the data from a form (following the normal rules for what controls count as successful)
data = that.serialize()
Since the checkboxes have the same value for the name attribute they are overwriting the same property on the data object.
that.find('[name]').each(function(index, value) {
var that = $(this), name = that.attr('name'), value = that.val();
data[name] = value; //This overwrites the property
});
Look at using jQuery's serialize function instead of building your own object to pass.
JS fiddle: http://jsfiddle.net/7Aysb/

Categories

Resources