get radio value using jquery using .prop - javascript

I want a form where the user has 3 different radio buttons and once one is clicked a different message will display depending on which radio button they pick.
Here is some of my code:
if ($('#Jordanstown').prop('checked'))
{
alert("Yeah, we are on the same campus")
}
if ($('#Belfast').prop('checked')) {
alert("Ah, we are not on the same site")
}
<form name ="mycampous">
<input type ="radio" name ="Jordanstown">Jordanstwon</input>
<input type ="radio" name ="Belfast">Belfast</input>
<input type = "button" value="select" onclick= "campous();"> </input>
</form>

I'll change your HTML little bit to add a class to all radio buttons so that I don't have to use the input[type='radio'] selector which is slow.
Also radio buttons should have same name, if you want only one of them to be selected at any given time, so you need to mention some value to differentiate between two radio buttons like below
<form name ="mycampous">
<input class="radio" type ="radio" name="city" value ="Jordanstown">Jordanstwon</input>
<input class="radio" type ="radio" name="city" value ="Belfast">Belfast</input>
<input type = "button" value="select" onclick= "campous();"> </input>
</form>
And then in your script, look for the change event on these radio buttons
$(document).ready(function(){
$('.radio').on('change', function(e){
var radioValue = $(this).val();
if(radioValue === 'Jordanstown'){
alert("Yeah, we are on the same campus");
} else if(radioValue === 'Belfast'){
alert("Ah, we are not on the same site");
}
});
});
Here's a bin to play with :)

Try something like this:
<script>
function campous(){
var value = $("[name='mycampous']").find("input[type='radio']:checked").val();
alert(value);
}
</script>
<form name="mycampous">
<input name="campus" type="radio" value="Jordanstown">Jordanstwon</input>
<input name="campus" type="radio" value="Belfast">Belfast</input>
<input type="button" value="select" onclick="campous();"> </input>
</form>
http://jsfiddle.net/p7Lj1bL6/

Try:
<input type ="radio" name ="Jordanstown" id="Jordanstown">Jordanstwon</input>
<input type ="radio" name ="Belfast" id="Belfast">Belfast</input>
<input type = "button" value="select" onclick= "campous();"> </input>
</form>
I added the id attributes since $('#Belfast') is selector for the ID not NAME.
I take it that you have the javascript sample wrapped in click event, something like this:
$('form').on('click', ':radio', function(){
if ($('#Jordanstown').prop('checked'))
{
alert("Yeah, we are on the same campus");
}
if ($('#Belfast').prop('checked')) {
alert("Ah, we are not on the same site");
}
});
Preferably, you should also have given the form an id to narrow down the DOM search.
EDIT
I just re-read your question. You're trying to alert the clicked radio. It should be:
$('form#ID_OF_FORM').on('click', ':radio', function(){
if( $(this).is('#Jordanstown') ){
alert("Yeah, we are on the same campus");
}else{
alert("Ah, we are not on the same site");
}
});
Provided your form's ID is ID_OF_FORM.

Related

Associate a checkbox with an input field and make it mandatory only if input value exists

I am trying to make a manual verification system and want the user to check each checkbox associated with individual inputs if a value exists before submission else the form would throw an error.
I have implemented this, but it does not seem to work. Also, I was wondering if there was a better way of achieving the same wherein we avoid passing the parameters to the function.
Similar to how we can associate a submit button for a form using form by supplying the id.
<form>
<input type="text" name="inputFieldOne">
<input type="checkbox" onblur="makeSureItIsSelected('inputFieldOne', 'inputCheckboxOne')" name="inputCheckboxOne">
<input type="text" name="inputFieldTwo">
<input type="checkbox" onblur="makeSureItIsSelected('inputFieldTwo', 'inputCheckboxTwo')" name="inputCheckboxTwo">
<input type="submit" value="Submit">
</form>
<script>
function makeSureItIsSelected(field, checkbox){
let fieldBox = document.getElementsByName(field)[0];
if(fieldBox.value != ''){
checkBox = document.getElementsByName(checkbox)[0];
checkBox.required = true;
}
}
</script>
If you want to set the checkbox to be required when the field has a value, you should hook an event on the field, not the checkbox. input would make a good event for this:
function makeSureItIsSelected(field, checkbox){
let fieldBox = document.getElementsByName(field)[0];
let checkBox = document.getElementsByName(checkbox)[0];
// Require the checkbox when the field has a value
checkBox.required = fieldBox.value != '';
}
<form>
<input type="text" name="inputFieldOne" oninput="makeSureItIsSelected('inputFieldOne', 'inputCheckboxOne')">
<input type="checkbox" name="inputCheckboxOne">
<input type="text" name="inputFieldTwo" oninput="makeSureItIsSelected('inputFieldTwo', 'inputCheckboxTwo')">
<input type="checkbox" name="inputCheckboxTwo">
<input type="submit" value="Submit">
</form>
Note that there's no need for those calls to getElementsByName: Just pass this into the function, and use nextElementSibling to access the checkbox:
function makeSureItIsSelected(field){
// Require the checkbox when the field has a value
field.nextElementSibling.required = field.value != '';
}
<form>
<input type="text" name="inputFieldOne" oninput="makeSureItIsSelected(this)">
<input type="checkbox" name="inputCheckboxOne">
<input type="text" name="inputFieldTwo" oninput="makeSureItIsSelected(this)">
<input type="checkbox" name="inputCheckboxTwo">
<input type="submit" value="Submit">
</form>
That said, it seems odd to have the checkboxes at all. The presence of the field in the form data should be sufficient. But if the checkbox's value has to be in the form data, simply add it on submit without having a checkbox at all.

select checkbox by name and check if it checked javascript

I am trying to test if checkbox is checked.
I have more inputs and they have different names.
I managed to select the input but I can't seem to check if it wa selected. If I add to the condition '= true' it is checked once I load the page. If I leave it just .checked it doesn't do anything
Have I selected the input right? Please note I want to select it by name rather than id or class
Why is it that once the page loads my condition for if statement doesn't work?
<input type="checkbox" name="name1">
<input type="checkbox" name="name2">
<input type="checkbox" name="name3">
<input type="checkbox" name="name4">
const firstInput = document.getElementsByName('name1');
if (firstInput[0].checked) {
console.log('checked');
}
You are selecting element with name "1" but don`t have element with such name.
If you want to select all inputs which name attribute starts with "name":
const firstInput = document.querySelectorAll('[name^=name]')
You need to add attribute to that input. Attach an onclick listener and invoke
getAttribute
setAttribute
to manipulate 'checked' attribute;
<input type="checkbox" onclick="myFunction()" name="name1">
<input type="checkbox" onclick="myFunction()" name="name2">
<input type="checkbox" onclick="myFunction()" name="name3">
<input type="checkbox" onclick="myFunction()" name="name4">
function myFunction() {
var $element = document.getElementsByName('name1')[0];
var checked = $element.getAttribute('checked') === 'true';
$element.setAttribute('checked', !checked);
console.log($element.getAttribute('checked'));
}

Choosing among radio buttons and Text Field

I have 2 radio buttons. All of them have different values. I also have one text field, in case I need a different value, I can enter that value on that text field.
<form action="" onsubmit="return doSubmit(this)">
<input type="radio" name="url" value="https://example.com/fee/25"> $25
<input type="radio" name="url" value="https://example.com/fee/50"> $50
<input type="submit" value="Submit">
</form>
and here is the Javascript I've found to make radio buttons working
<script type="text/javascript">
function doSubmit(form) {
var urls = form['url'];
var i = urls && urls.length;
while (i--) {
if (urls[i].checked) {
window.location = urls[i].value;
}
}
document.getElementById("amount").value;
return false;
}
</script>
I have one text field:
<input type="text" name="amount" size="10" id="amount" value="">
Ok. If the amount is entered, then I need to use this code:
document.getElementById("amount").value
But how to make it working with radio buttons? I have created this JS code:
<script type="text/javascript">
var link = "https://example.com/fee/";
var input= document.getElementById('amount');
input.onchange=input.onkeyup= function() {
link.search= encodeURIComponent(input.value);
};
</script>
What I'm doing wrong? Thanks in advance for your time. I love and enjoy learning from experts.
I would create a separate radio button for the text input:
var options = Array.from(document.querySelectorAll("[name=url]"));
amount.addEventListener('focus', function() {
options[0].checked = true; // If textbox gets focus, check that radio button
});
options[0].addEventListener('change', function() {
amount.focus(); // if first radio button gets checked, focus on textbox.
});
function doSubmit(form) {
// get checked value, replace empty value with input text
var value = options.find( option => option.checked ).value || amount.value;
window.location = "https://example.com/fee/" + value;
return false;
};
<form action="" onsubmit="return doSubmit(this)">
<input type="radio" name="url" value="" checked>
$<input type="text" name="amount" size="5" id="amount" value="" >
<input type="radio" name="url" value="25"> $25
<input type="radio" name="url" value="50"> $50
<input type="submit" value="Submit">
</form>
Instead of using the url as the value for the radio buttons, consider using the value you wish to pass to the url:
function doSubmit(form) {
var endpoint = "https://example.com/fee/";
// gets the values of input elements that were selected
var checkedValues = Array.from(form.amounts)
.filter(radio => radio.checked)
.map(radio => radio.value);
// if a radio button was checked, use its value
// otherwise, use the value in the text field
var amount = checkedValues.length ?
checkedValues[0] : form.amount.value;
console.log('redirecting to: ', endpoint + amount);
return false;
}
// uncheck radio buttons when text is entered
function uncheck() {
Array.from(document.querySelectorAll('input[name="amounts"]'))
.forEach(radio => radio.checked = false);
}
<form action="" onsubmit="return doSubmit(this)">
<input type="radio" name="amounts" value="25"> $25
<input type="radio" name="amounts" value="50"> $50
<input type="text" name="amount" onkeyup="uncheck()">
<input type="submit" value="Submit">
</form>
Edit: Wow I completely forgot you could use the :checked attribute as a css selector. In this case, the code becomes quite simple:
function doSubmit(form) {
// select checked inputs with the specified name attribute
var checkedRadio = document.querySelector('input[name="amounts"]:checked')
// if we have a radio button that is checked, use its value
// otherwise, use the text input's value
var amount = checkedRadio ? checkedRadio.value : form.amount.value;
window.location = 'https://example.com/fee/' + amount;
return false;
}
// uncheck radio buttons when text is entered
function uncheck() {
Array.from(document.querySelectorAll('input[name="amounts"]'))
.forEach(radio => radio.checked = false);
}
<form action="" onsubmit="return doSubmit(this)">
<input type="radio" name="amounts" value="25"> $25
<input type="radio" name="amounts" value="50"> $50
<input type="text" name="amount" onkeyup="uncheck()">
<input type="submit" value="Submit">
</form>

Is it possible to assign value of text-field to radio button

I am providing multiple check-box and radio button when i enter any value in text field than the same value will assign to radio button and How it is possible using jQuery. Below is the image for reference. I am storing Question and multiple answer and i am going to store true answer out of them like shown in image.
$data = array();
for($i=0,$j=1;$i<count($_REQUEST['quiz_options']);$i++,$j++)
{
$data["quiz_Options".$j] = $_REQUEST['quiz_options'][$i];
}
$data["quiz_Id"] = $Quiz_ID;
$data["quiz_Correct_Answer"] = $_REQUEST['quiz_opt'];
$quiz->insertOptions($data,'quizoptions');
<input class="col-md-4" type="text" name="quiz_options[]" value=""/>
<input type="radio" name="quiz_opt[]" value=""/>
//Here I want to assign my textfield value to the radio button when i write something in my text field.
Please see the example here
You could attach a keydown event to the the textbox and update the value of the radiobutton.
something like this(pseudocode):
$('#textboxId').on('keydown',function(){
$('#radiobuttonId').val($(this).value);
});
Maybe you can use a data attributes (HTML5)
Example
:)
You have to on blur or onchange and should use one class for all dynamic textbox creation. try this code
<input name="quiz_options[]" class ="changesNo1" value="" />
<input name="quiz_options[]" class ="changesNo1" value="" />
<input name="quiz_options[]" class ="changesNo1" value="" />
<input type=radio value="" name="quiz_opt[]">
<input type=radio value="" name="quiz_opt[]">
<input type=radio value="" name="quiz_opt[]">
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.7.1/jquery.min.js" type="text/javascript"></script>
<script type="text/javascript">
var test_arr = $("input[name='quiz_options[]']");
$(document).on('change keyup blur','.changesNo1',function(){
$.each(test_arr, function(i, item) {
$("input[name='quiz_opt[]']").val($(item).val());
var d=$("input[name='quiz_opt[]']").val(); // your reference
//alert(d); // This alert for your reference
});
});
</script>

how to get the value of the hidden fields in here after the radio button is clicked

Am trying to get the value of the hidden input fields on every click of a radio button. I have just posted a single div. I have a multiple div with same structure. I have successfully obtained the value of radio button but I want to get the value of hidden input now.
<div class="QA">
<h1> First Question</h1>
<input type="radio" id="check" name="q" value="A">Options 1</input>
<input type="radio" id="check" name="q" value="B">Options 2</input>
<input type="radio" id="check" name="q" value="C">Options 3</input>
<input type="radio" id="check" name="q" value="D">Options 4</input>
<input type="hidden" id="result" value="B" />
<br/>
<div id="result"></div>
</div>
<script>
$(document).ready(function() {
$("input:radio").change(function() {
checkResult(this);
});
});
function checkResult(el)
{
$this=$(el).parent("div.QA");
$this.slideUp();
}
</script>
Maybe you could try removing the hidden input entirely and indicate the correct answer using a data-* attribute. Something like:
<div class="QA" data-answer="B">
Then in your checkResult function you could retrieve this value using
function checkResult(el)
{
$this=$(el).parent("div.QA");
var answer = $this.data("answer");
$this.slideUp();
}
function checkResult(el)
{
$this = $(el).parents("div.QA");
$this.slideUp();
var x = $this.find('#result').val(); //find value of hidden field in parent div
}
Change your markup
multiple id's should not be used. Use class instead.
<input type="radio" id="check" name="q" value="A">Options 1</input>
to
<input type="radio" class="check" name="q" value="A">Options 1</input>
var $hidden=$(el).siblings("input[type='hidden']");
BTW you have lot of elements with same ID, not good
You can get the value of the hidden element by it's id.
var hiddenValue = $("#result").val();
You can use this in hidden function
function checkResult(el)
{
var hiddenValue = $("#result").val();
alert(hiddenValue);
}

Categories