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>
Related
both simple and complicate question:
I have my dropdown item created programmatically from ajax request and that is ok. So i serve name and surname for convenient aestetic way, but i need to send an ajax post with only surname and value is needed for other purposes.
$('#dropDocente').append('<option value="'+value.idDocente+'"">' + value.surname + ' ' + value.name +'</option>');
what i would achieve is:
var testd = $("#dropDocente option:selected").text();
console.log("Surname is : "+testd);
desired output == Surname is : Doe
so, in other hand, i would like get only first element of text in selected dropbox.
I can help me to understand how to reach my goal?
In jQuery, you don't use the .text() method to get the value of a dropdown menu. You need to just have:
var testd = $("#dropDocente").val();
and that will return the selected option's value from the dropdown.
you can add value.surname as a data-surname data tag onto the option and then retrieve that value by selecting the option and using .data('surname'). you can do this for any other value you want to single out as well
$(document).ready(function() {
var values = [
{ surname: "Doe", name: "John", idDocente: "some value here" },
{ surname: "Shmo", name: "John", idDocente: "some value here2" },
{ surname: "Little", name: "John", idDocente: "some value here3" },
];
for (var i = 0; i < values.length; i++) {
var value = values[i];
$('#dropDocente').append('<option value="'+value.idDocente+
'" data-surname="'+ value.surname +'">' + value.surname + ' '
+ value.name +'</option>');
}
// default first
$('.results').text($("#dropDocente option:first").data('surname') + ', ' + $("#dropDocente option:first").val());
// on change, get the surname
$('#dropDocente').on('change', function() {
$('.results').text($("#dropDocente option:selected").data('surname')+ ', ' + $("#dropDocente option:selected").val());
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<select id="dropDocente">
</select>
<br/><br/><br/>
<div class="results">
</div>
You could just split full name on select change.
Something like this:
$('select').on('change', function(){
var id = $(this).val();
var fullName = $('select option:selected').text();
var surname = fullName.split(" ", 1);
});
Full example here: https://jsfiddle.net/1aj06Lw6/1/
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();
I've created a portion of my content through using jQuery to make the same content for each item in my list. It has all worked perfectly except for the last entry. For some reason it acts weird.
An input field is created for each entry that only accepts 2 characters. I have an error script that will parse the entry and see if it's valid. I am only accepting numbers below 61 in this case. All the inputs work except for the last entry.
Additionally, the labels for the 3 inputs created are not putting focus on the respected input value for this entry.
My problem is I don't know why the last entry doesn't work whereas the others will. Can someone explain?
Below are a few functions used.
Populate.js (Used to create content from list)
var $parent = $('div#heroes');
var prestige = '<option value="0">None</option><option value="1">Prestige 1</option><option value="2">Prestige 2</option><option value="3">Prestige 3</option><option value="4">Prestige 4</option><option value="5">Prestige 5</option>'
$.each(heroes, function(index,value) {
$div = $('<div id="hero' + index + '"></div>');
$div.append('<h6>' + value + '</h6>');
$div.append('<span id="active"><input type="checkbox" id="isActive' + index + '" /><label for="isActive' + index + '">Is Active?</label></span>');
$div.append('<span id="level"><label for="level' + index + '">Level: </label><input type="text" size="2" maxlength="2" id="level' + index + '" /></span>');
$div.append('<span id="prestige"><label for="prestige' + index + '">Prestige: </label><select id="prestige' + index + '">' + prestige + '</select></span>');
$parent.append($div);
});
errors.js (Parses the input value and prints the error if not a integer below 61)
$.each(heroes, function(index,value){
$('input#level' + index).change(function() {
var val = $('input#level' + index).val();
if(val > 60) {
alertify.log("Hero " + value + " cannot be above Level 60!", "", 0);
$('#level' + index).addClass('error');
} else if( isNumeric(val) ) {
if( $('#level' + index).hasClass('error') ) {
$('#level' + index).removeClass('error');
}
} else {
alertify.log("Only numbers are accepted.");
$('#level' + index).addClass('error');
}
});
});
function isNumeric(num){
return !isNaN(num);
}
The list used:
var heroes = ["Black Panther","Black Widow","Cable","Captain America","Colossus","Cyclops","Daredevil","Deadpool",/*"Doctor Strange",*/"Emma Frost",
"Gambit","Ghost Rider","Hawkeye","Hulk","Human Torch","Iron Man","Jean Grey",/*"Juggernaut",*/"Loki","Luke Cage",/*"Magneto","Moon Knight",*/"Ms Marvel",
"Nightcrawler",/*"Nova","Psylocke",*/"Punisher","Rocket Raccoon",/*"Silver Surfer",*/"Scarlet Witch","Spider-Man","Squirrel Girl",/*"Star-Lord",*/"Storm",
/*"Sue Storm",*/"Thing","Thor","Wolverine"/*,"Venom"*/];
You can view the page at http://spedwards.cz.cc/new.html
I am still accepting answers. I am stumped to why this isn't working as expected.
Ok I figured out my problem. I'm using the bx-slider plugin and it creates a clone of the last element before the first and a clone of the first, after the last. So my function was getting the clone.
All I had to do was add :not(.bx-clone) to the selector.
So instead of $('input#level' + index); it changed to $('input#level' + index + ':not(.bx-clone)');
Please check the JSFIDDLE , the rel attribute in the alert comes out as 'undefined' :
var ItemTypeArray = $('input[name^=ItemType]:checked').map(function(){
alert(this.id + ' , r= ' + this.rel);
return this.rel + '--' + this.value;
}).get().join(",");
Also , this function gives a string , but I need an array to be constructed to post it.
There's no such attribute called rel on an input (there is on a link tag however). You should really use data attributes instead:
<input id="SOLD[1]" value="1" name="ItemType[1]" type="radio" data-rel="1">
<input id="PURCHASED[1]" value="2" name="ItemType[1]" type="radio" checked="checked" data-rel="1">
Then you can do:
var ItemTypeArray = $('input[name^=ItemType]:checked').map(function () {
alert(this.id + ' , r= ' + $(this).data("rel"));
return $(this).data("rel") + '--' + this.value;
}).get().join(",");
Or to return what you stated in comments (an array), you can do:
var ItemTypeArray = [];
$('input[name^=ItemType]:checked').each(function () {
ItemTypeArray.push(this.id + ' = ' + $(this).data("rel"));
});
See HERE
I just included jquery and modified your code as follows. Use $(this).attr('rel') instead of this.rel
var ItemTypeArray = $('input[name^=ItemType]:checked').map(function () {
alert(this.id + ' , r= ' + $(this).attr('rel'));
return this.rel + '--' + this.value;
}).get().join(",");
Here is the jsfiddle
try
$(this).attr("rel")
this will get you an attribute value named 'rel'
I am appending the checkboxes in a particular class using some function.. I have a function to run everytime the checkbox is selected.. So I need to get the name and id of the Checkboxes..
Heres the part of the code where I am appending the checkbox dynamically.. Here value is the one I want the id and name attribute to be..
$.each(brandNameg, function(key, value) {
$(".fpblocks .fpblocksBrands_inner ul").append("<label class='checkbox'><input type='checkbox' onclick='selectMainBrand(\"" + value + "\");' />" + value + "</label>");
});
set the id using
$.each(brandNameg, function(key, value) {
$(".fpblocks .fpblocksBrands_inner ul").append('<label class="checkbox"><input type="checkbox" id="' + value + '" onclick="selectMainBrand("' + value + '");" />' + value + '</label>');
});
function selectMainBrand(ids) {
$('#Brands').on("change", "input", function () {
console.log("called");
var selected = this.name;
console.log(selected);
});
}
I'm assuming your UL tag has id="brands". If not change the above code as follows
$('.fpblocks').on("change", "input", function () {
$.each(brandNameg, function(key, value) {
$(".fpblocks .fpblocksBrands_inner ul").append("<label class='checkbox'><input type='checkbox' id ='someID' name ='someName' />" + value + "</label>");
});
and on checkbox click..
$(".fpblocks .fpblocksBrands_inner ul :checkbox").live('click', function(){
var id = $(this).attr('id'); //get id of checked checkbox
var name = $(this).attr('name'); //get name of checked checkbox
})
remove onclick='selectMainBrand(value);' from inputs' generation code
After checkboxes are generated, you can select name and
$('#Brands input').on("change", function () {
var name=$(this).attr("name");
var id=$(this).attr("id");
alert(name);
alert(id);
console.log(selected);
});
see the DEMO http://jsfiddle.net/BbtEG/
Your dynamically created html (<input type='checkbox' onclick='selectMainBrand(value);' />) does not have a name, or an id. You cannot pass what doesn't exist. To solve this, generate a name and an id to use.
Also in your selectMainBrand function you don't appear to be using the ids parameter that you're passing in. All that function is doing is binding a handler to the input which, since you're using on to bind it, seems silly.
Why not use on to delegate the handler instead? If you delegate the handler, you can grab the name or id from within the handler thereby obviating the need to pass those in as parameters (working demo).
$.each(brandNameg, function (key, value) {
var label = $('<label />').addClass('checkbox'),
input = $('<input />').attr({
"type": "checkbox",
"name": "mainBrand" + key, //set the name, appending the key to make it unique
"id": "mainBrand" + key //set the id, appending the key to make it unique
});
$(".fpblocks .fpblocksBrands_inner ul").append(label.append(input).append(value));
});
//delegate the change handler
$('.fpblocks .fpblocksBrands_inner').on("change", '#Brands input', function (e) {
var selectedName = this.name,
selectedId = this.id,
isChecked = this.checked;
console.log(JSON.stringify({
"called": true,
"selectedName": selectedName,
"selectedId": selectedId,
"isChecked": isChecked
}));
});
If you truly have your heart set on passing in the parameters, there are ways to do that, such as binding the handler within the loop where you create the inputs (working demo):
$.each(brandNameg, function (key, value) {
var label = $('<label />').addClass('checkbox'),
input = $('<input />').attr({
"type": "checkbox",
"name": "mainBrand" + key, //set the name, appending the key to make it unique
"id": "mainBrand" + key //set the id, appending the key to make it unique
}).click(function (e) {
var self = $(this), // capture the input as a jQuery object (typically very useful)
actualHandler = function (id, name) {
// do stuff
console.log(JSON.stringify({
"called": "actualHandler",
"selectedName": id,
"selectedId": name,
"isChecked": self.prop('checked')
}));
};
actualHandler(this.id, this.name);
// or
actualHandler(self.attr('id'), self.attr('name'));
});
$(".fpblocks .fpblocksBrands_inner ul").append(label.append(input).append(value));
});
or you could set the onchange attribute in the loop where you create the inputs (working demo):
window.inputHandler = function (id, name) { // must be added to the global scope, otherwise it won't be visible.
// do stuff
console.log(JSON.stringify({
"called": "inputHandler",
"selectedName": id,
"selectedId": name
}));
};
$.each(brandNameg, function (key, value) {
var label = $('<label />').addClass('checkbox'),
input = $('<input />').attr({
"type": "checkbox",
"name": "mainBrand" + key, //set the name, appending the key to make it unique
"id": "mainBrand" + key, //set the id, appending the key to make it unique
"onchange": "inputHandler('" + "mainBrand" + key + "', '" + "mainBrand" + key + "')"
});
$(".fpblocks .fpblocksBrands_inner ul").append(label.append(input).append(value));
});
and there are other ways to go about it.
Personally, I would use the delegation.