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'
Related
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>
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
I'm trying to assign variable value to dynamically created input elements. But I couldn't. The input elemts are created but not with id.
$(document).ready(function(){
// Declaring global variables
var cnt = 1;
var fooId = "foo";
var cnt1 ='aaaa';
// Code for Changing the datalist for second input testingphase when ever first input Tasks has been changed.
$("#tasks" + cnt).change(function () {
$("#activitytype" + cnt).replaceWith('<input id="activitytype" + ctn value="asasa" name="ActivityType" placeholder="ActivityType" >');
if (bla1 == 'Service Request') {
$("#testingphase" + cnt).replaceWith('<input id="testingphase" + ctn list="Service Request" name="Tasks" placeholder="Tasks2">');
// changingactivity ();
}
You have to change your replaceWith method slightly to include the variable without quotes. Change:
$("#activitytype" + cnt).replaceWith('<input id="activitytype" + ctn value="asasa" name="ActivityType" placeholder="ActivityType" >');
To something like:
$("#activitytype" + cnt).replaceWith('<input id="activitytype' + ctn + '" value="asasa" name="ActivityType" placeholder="ActivityType" >');
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)');
I have this JavaScript that adds a form field, along with a link to remove that field:
var fieldCount = 0;
function addField() {
var name = 'file' + fieldCount;
var row = 'row' + fieldCount;
var str = '<p id="' + row + '"><label for="' + name + '">File to upload: <input type="file" name="' + name + '" id="' + name + '" />(100MB max size) <a onclick="removeRow(' + row + '); return false;">[-]</a></label></p>';
fieldCount++;
$("#fields").append(str);
};
function removeRow(id) {
$(id).remove();
};
Here is the markup:
<form id="ajaxUploadForm" action="<%= Url.Action("AjaxUpload", "Upload")%>" method="post" enctype="multipart/form-data">
<fieldset id="uploadFields">
<legend>Upload a file</legend>
<div id="fields"></div>
<input id="ajaxUploadButton" type="submit" value="Submit" />
</fieldset>
<a onclick="addField(); return false;" id="add">Add</a>
<div id="resultBox">
<p id="status" style="margin:10px;"></p>
</div>
</form>
The addFields works as expected, but when I click the remove link firebug tells me that row# is not defined, where # is any number of the added fields.
Any help would be appreciated!
You need to pass a valid selector expression for an ID selector (#ID), either in the removeRow call (also note the quotes surrounding the ID selector):
'<a onclick="removeRow(\'#' + row + '\'); return false;">'
Or in the removeRow function itself:
function removeRow(id) {
$("#" + id).remove();
};
You need to have quotes around it, since it's a string.
You also need the "#" to make it into a selector:
var str = '... <a onclick="removeRow(\'#' + row + '\'); return false;">...';
A better way would be to assign the onclick as a function (not sure of the jQuery way to do this but in plain Javascript):
var a = document.createElement('a');
a.onclick = (function(row)
{
return function()
{
removeRow(row);
return false;
};
})();
You are passing in the string value of row12, but the selector should be:
$('#'+row).remove()
The # specifies that you are looking for an ID. I agree with what I think one of the other answers was about to say, you should just use the onclick events natural this keyword instead:
<p onclick="remove(this)">something</p>
function remove(what) {
$(what).remove()
}
Or, maybe just forget the whole thing all together and switch to behavior for those kinds of rows:
$('.removableRow').live('click', function() {$(this).remove()});
Then you just specify that the row is removable, and never have to worry about binding events at all:
<p><a class="removableRow" href="#">Remove</a></p>