I'm trying to get the value of a selected radio button with jQuery. I generate my html-elements with jquery from a json-template, this is my code for generating radio buttons:
function AddRadio(labelName, buttons, i, paneIndex, dataID) {
$('#Ctabs1-pane' + paneIndex + '').append('<div class="form-group"><label class="col-lg-2 control-label">' + labelName + '</label><div class="col-lg-10" id="' + dataID + '"></div></div>');
$.each(buttons, function (j, value) {
$('#' + dataID).append('<div class="radio"><label><input type="radio" name="optionsRadios" value="' + value + '">' + value + '</label></div>');
});
}
i try to get the selected radiobutton with this code:
return $("input[type='radio'].radioBtnClass:checked").val();
But this gives me undefined
What am i doing wrong?
Your selector match input element with class radioBtnClass but you're not added it when append. Either add that class into your input:
$('#' + dataID).append('<div class="radio"><label><input type="radio" class="radioBtnClass" name="optionsRadios" value="' + value + '">' + value + '</label></div>');
or target it by name instead:
$("input[type='radio'][name='optionsRadios']:checked").val();
Related
In my javascript code, i am able to output the id of a the selected item. I want to pass the id to my controller. I appended the input(created in the JS code) to my html form so as to get the id of the selected item but it wouldn't do the trick.
*HTML**
<form>
// inputs for form in here
</form>
JS
$(".myItem").append(
'<p name="item_id" id="item_id">Item ID: ' + item.id + '</p>').appendTo('form');
Controller
$getID = Input::get('item_id');
$fetchItem = Item::all()->where('id',$getID)->first();
Try to append an input element instead of a p:
$(".myItem").append(
'<input name="item_id" id="item_id" value=' + item.id + ' />).appendTo('form');
You can even have both; 1 to store the value (input) and the other to show it on screen (p).
$(".myItem").append('
<input type="hidden" name="item_id" id="item_id" value=' + item.id + ' />
<p>Item ID: ' + item.id + '</p>').appendTo('form');
I'm using a set of arrays to populate some radio selects on a page
//holds the set value of the variable
var universalVariables = [thing1, thing2, thing3];
//used for the classes in the radios to get values later
var universalNames = ['thing1','thing2','thing3'];
//used to put a label on each radio
var universalAttributes = ['THING ONE', 'THING TWO', 'THING THREE'];
Followed by:
$.each(universalVariables, function(index, val) {
$('#universalAttributes').append('<br />' + universalAttributes[index] + '<br /><div class="radio"><label><input type="radio" name="' + universalNames[index] + '" value="false">FALSE</label></div><div class="radio"><label><input type="radio" name="' + universalNames[index] + '" value="true">TRUE</label></div>')
});
//set data
$.each(universalVariables, function(index, val) {
if (universalVariables[index] == false) {
$("input[name=" + universalNames[index] + "][value=false]").prop('checked', true);
} else if (universalVariables[index] == true) {
$("input[name=" + universalNames[index] + "][value=true]").prop('checked', true);
}
});
This creates three (because there are three variables in my arrays) radios, but obviously can handle as many as you want. All you need to do is supply the information in the arrays (versus coding the radio selects themselves).
The three pieces of information here
The problem comes in when you have to add a variable. Ideally, I'd like to generate the first two arrays. I could supply the list of words and then generate. The trick (for me anyway) is doing this where one array has string names and the other needs the variable NAMES not the variable VALUES.
There has to be a simple way of doing this. Open to any suggestions.
You can store the "metadata" of the variables in an object, and access them by a key that matches up with the variable name, like so:
You can also set the checked property at the same time you append the input to the container, eliminating the need for that second loop.
var universalVariables = {
"thing1": {
value: true,
attribute: "THING ONE"
},
"thing2": {
value: false,
attribute: "THING TWO"
},
"thing3": {
value: true,
attribute: "THING THREE"
},
};
// used so we can guarantee correct sequential order
var universalNames = ['thing1','thing2','thing3'];
$.each(universalNames, function(index, name) {
var objVar = universalVariables[name];
$('#universalAttributes')
.append('<br />' + objVar.attribute +
'<br /><div class="radio"><label><input type="radio" name="' + name +
'" value="false"' + (objVar.value ? '' : 'checked') + '>FALSE</label></div><div class="radio"><label><input type="radio" name="' + name +
'" value="true"' + (objVar.value ? 'checked' : '') + '>TRUE</label></div>')
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="universalAttributes"></div>
So this is what the page looks like currently:
The first one is hardcoded in and then the rest are added/removed by the buttons. The first one can also be added and removed from the buttons. I want to call a jquery function when the dropdown is changed to change the type from textbox/radiobutton (and text)/checkbox (and text) etc.
Currently it only works on the first Question/Answer and only works if it is the original and not dynamically created. I'm not sure why that is.
Here is how the Q/A's are created and removed
$("#addButton").click(function () {
if (counter > max_fields) {
alert("Only " + max_fields + " Questions allowed");
return false;
}
var newTextBoxDiv = $(document.createElement('div'))
.attr("id", 'TextBoxDiv' + counter);
newTextBoxDiv.after().html('<label>Question #' + counter + ' : </label>' +
'<input type="text" name="textbox' + counter +
'" id="questionbox' + counter + '" value="" />' +
' <select id="choice'+ counter +'"><option>Type</option><option>Radio Button</option><option>Text Box</option><option>Check Box</option></select>' +
'<button id = "remove' + counter + '">Remove</button>' +
'<br/><label>Answer #' + counter + ' : </label>' +
'<div id="Answers' + counter + '">' +
'Option 1: <input type="text" id="answerbox' + counter +
'1" name="answerbox' + counter + '" value="" />' +
'<br/>Option 2: <input type="text" id="answerbox' + counter +
'2" name="answerbox' + counter + '" value="" />' +
'<br/>Option 3: <input type="text" id="answerbox' + counter +
'3" name="answerbox' + counter + '" value="" />' +
'<br/>Option 4: <input type="text" id="answerbox' + counter +
'4" name="answerbox' + counter + '" value="" /></div>');
newTextBoxDiv.appendTo("#TextBoxesGroup");
counter++;
});
$("#removeButton").click(function () {
if (counter == 1) {
alert("No more textbox to remove");
return false;
}
counter--;
$("#TextBoxDiv" + counter).remove();
});
This is how I tried to get it to change types
$('#choice1').change(function () {
var selected_item = $(this).val()
var searchEles = document.getElementById("Answers1").children;
alert(searchEles.length);
for(var i = 0; i < searchEles.length; i++) {
$('#answerbox1' + i).attr('type', selected_item);
//alert(searchEles.length);
}
});
The web page code is as follows
<input type='button' value='Add Question' id='addButton'/>
<input type='button' value='Remove Question' id='removeButton'/>
<div id='TextBoxesGroup'>
<div id="TextBoxDiv1">
<label>Question #1 : </label>
<input type='text' id='questionbox1'/>
<select id="choice1" onchange="$('#choice').val('id');"> //this on change was added and currently does nothing it seems.
<option value="">Type</option>
<option value="radio">Radio Button</option>
<option value="text">Text Box</option>
<option value="checkbox">Check Box</option>
</select>
<button id="remove1">Remove</button>
<br/><label>Answer #1 : </label>
<div id="Answers1">
Option 1: <input type="text" id='answerbox11' name='answerbox1' value="" />
<br/>Option 2: <input type="text" id='answerbox12' name='answerbox1' value="" />
<br/>Option 3: <input type="text" id='answerbox13' name='answerbox1' value="" />
<br/>Option 4: <input type="text" id='answerbox14' name='answerbox1' value="" />
</div>
</div>
</div>
I tried to do something like onchange and then get the ID and go from there but that didn't work. I know it doesn't match the back end jquery name.
TL;DR
I don't know how to dynamically write the jQuery function to work
for all of them.
I don't know why even if I hardcode it to #choice1 it will work
when its first created but not if i remove and add it even though it
has the same exact values. I think it might MAYBE have to do with
for loop, because the alert doesn't even trigger the second time
around.
You could try
$(document).on("change", ".selector", function(){
//do something
});
//Edit
Add to the select element class for example select-option and a tag that will hold the select's counter
//JS
...'<select id="choice'+counter+'" class="select-option" number="'+counter+'">'...
and then your on change function would look something like
$(document).on("change", ".select-option", function(){
//do something
var selected_type = $(this).attr('value');
var ans_number = $(this).attr('number');
$("#answerbox"+ans_number).children('input').attr('type', selected_type);
});
I hope this will help :)
For dynamically added elements use
$(selector).on("change", callback)
If element is dynamic then Jquery will not bind directly as
$('#choice1').change(function (){});
But for that you need to call same function with some static element.
For Ex:
$(".listingDiv").find('#choice1').change(function (){});
or
$(document).find('#choice1').change(function (){});
and it will work. try it.
When elements will be aded dynamically, best practice is to delegate the handler(s). Put your handler on the containing div or window/document
.
First
<select id="choice1" onchange="$('#choice').val('id');"> //this on change was added and currently does nothing it seems.
This is one reason your never be called. If you bind an event listener to an element, you should not write the actual JS code inside the element.
Second
Bind your listener like this:
$('#choice1').on("change", function () {
var selected_item = $(this).val()
var searchEles = document.getElementById("Answers1").children;
alert(searchEles.length);
for(var i = 0; i < searchEles.length; i++) {
$('#answerbox1' + i).attr('type', selected_item);
//alert(searchEles.length);
}
});
I'm Having a bit of an issue. I'm using JavaScript to inset HTML into a webpage along with an event handler for the onblur event. It looks like this:
return '<input id = "txtIn" type="text" value=" ' + dateTime + '" onblur= "submitManualDate(document.getElementById("txIn").value(), 2, 3);" />';
I'm getting a syntax error. However, the following works perfectly fine:
return '<input id = "txtIn" type="text" value=" ' + dateTime + '" onblur= "submitManualDate(1, 2, 3);" />';
Any idea what I'm missing?
Using " inside "(double quoted) expression will break the string.
It's better to pass this as an argument as you should not have multiple elements with same id attributes in a document.
Try this example:
(function() {
var input = '<input type="text" value="5" onblur= "submitManualDate(this, 2, 3);" />';
document.getElementById('parent').innerHTML = input;
})();
function submitManualDate(elem, j, k) {
alert(elem.value + ' ' + j + ' ' + k);
}
<div id='parent'></div>
Fiddle here
The change events inside the bootstrap button dropdown is not functioning. What could be the reason? How to fix this?
Below is my fiddle. I wanted to fire a checkbox changed event but surprisingly the below code doesn't fire.
http://jsfiddle.net/20hLtzvr/18/
$('#chk0').click(function()
{
alert('hello world');
});
You forgot the " when you set the id
Replace
$('#citycountylist ul').append('<li><input type="checkbox" class="chk" id=' + 'chk' + index + ' />' + ' ' + json.NewYork[index].name + ' </li>');
By
$('#citycountylist ul').append('<li><input type="checkbox" class="chk" id="' + 'chk' + index + '" />' + ' ' + json.NewYork[index].name + ' </li>');