I' m using MVC and set an itemId attribute to checkboxes.
#Html.CheckBox("check", false, new { itemId = item.ID })
Now I want to get this attribute with using javascipt but I could not.
I got the checkboxes list with this code:
var checkboxes = document.getElementsByName('check');
Are there any solution for it?
this should help:
var itemId = document.getElementsByName('check')[0].getAttribute('itemId');
Related
I have a datatable containing a list of Cars. each row in the html contains a Car ID. I have added checkbox column to the first cell in my datatable - if it is checked the row is highligted to indicate to the user they have selected that row. What I waht to do is get all the IDs of all the cars a user has selected on clicking a button on the page. (also there are other columns in the table row where I have checkboxes (i.e - a Manual column or an Automatic column which will somtime be checked - like in column 5 ot 6 in the table)
so this is part of the cshtml for my page..
#foreach (var car in Model.Cars)
{
<tr carId="#Html.DisplayFor(modelItem => car.CarID)">
<td class="table-data">
<input id="SelectIndividual" name="Select" type="checkbox" />
</td>
//more stuff set in other tds in table
Then this is the JS I have for the page so far.
$('#GetSelectedCars').click(function (event) {
var cars= new Array();
carsListTable.find("tr").each(function (index, para) {
$('tr').find('td:input:checked:first').each(function () {
var car= new Object();
alert($(this).parent().parent().attr("carId"));
car.ID = $(this).parent().parent().attr("carId");
cars.push(car);
});
});
var jsonString = $.toJSON(cars);
I want to then return the json string to my controller (I do this by passing the value into a hidden field on my model and then deserialize - but at the minute I am getting it as empty. My problem is getting the best way to get the id from the row if it is checked?
You can use the selectors :checkbox:checked and use the jQuery.map to convert the array. The jQuery.closest() method will give the closest ancestor matching the given selector.
var cars = carsListTable.find('.table-data :checkbox:checked').map(function(i, v){
return {
ID : $(v).closest('tr').attr('carId')
}
});
Demo Fiddle
Note: The id of elements should be unique in a document so the id of the checkbox should be removed or has to be suffixed or prefixed by a dynamic value like the car id.
First, you should use class instead id for elements that will be present more than once. I suggest change #SelectIndividual for .SelectIndividual on the checkbox input). Another thing you should change is the carId attribute, because is not semantic valid. You should use custom data attributes instead. This is how your code should look like:
HTML
#foreach (var car in Model.Cars)
{
<tr data-carID="#Html.DisplayFor(modelItem => car.CarID)">
<td class="table-data">
<input id="SelectIndividual" name="Select" type="checkbox" />
</td>
Jquery
$('#GetSelectedCars').click(function (event) {
var cars= new Array();
$('SelectIndividual:checked').each(function () {
var car= new Object();
car.ID = $(this).parent().parent().data('carID');
cars.push(car);
});
});
//keep doing things
I would suggest to use the data-* attributes that are valid HTML5 as well as the jQuery.data() methods for the id of the car.
Can you assign a class to all checkboxes in first column and then try this
$('.cbClass:checked').each(function () {
tr = $(this).closest('tr');
// use the row
})
Using jsTree (pre1.0_fix_1), I would like to obtain a list of id's for all the checked items (or better, a JSON object with id AND text of each checked item). I will then make an ajax call with this. Additionally, this should happen any time there is a state change of something getting checked or unchecked.
This is what I currently have:
$(function(){
n = $('#colors').jstree({
"plugins": ["themes", "html_data", "checkbox"]
}).bind("change_state.jstree", function(e, data){
console.log($('#colors').jstree('get_selected').attr('id'));
});
});
This is just returning 'colors', from the container'sid: <div id="colors">. I fished around the data object, but didn't find it in there (perhaps I missed it?)
In order to get the checked nodes' JSON you should be using get_checked and not get_selected. Try this:
var checked = $("#colors").jstree("get_checked",null,true);
var checked_json = [];
$(checked).each(function (i,node) {
var id = $(node).attr("id");
var text = $(node).attr("text");
var node_json = {
"id" : id,
"text" : text
};
checked_json.push(node_json);
});
After that checked_json will contain an array of of id+text objects which you could send to the server.
I have a #htmlDropDownList as
#Html.DropDownList("MyList", new SelectList(Model.List, "Id", "Movie"))
in a mvc3 view.
How can I capture the selected value of this drop down list using javascript and use it to change the contents of the view according to the selected item?
To get the value is simple:
$('#MyList').val()
For the second part of the question I need more info.
UPDATE
How would we use the value?
//get the url for the movie description , define id as 0, so it is easier to replace lateron.
var moviedescriptionUrl = '#Url.Action("details", "movies", new { id = 0})';
//get the movieid
var movieID = $('#MyList').val();
//update a div
$('#movie-description').load(moviedescriptionUrl.replace('0', movieID));
Assuming I have an "details" action that return a partial view.
1 naga naga123
2 Tamil tamil123
3 vinod vinod123
4 naveen naveen123
5 jakkir jakkir123
save edit delete
UserID:
UserName:
Password:
I have check box at the end of each row. When I click the check box and select edit the values should get displayed in the text boxes corresponding to userId, userName & Password.
My js code for edit is
function Edit(){
var i=dwr.util.getValue("userId");
LoginManagement.selectId(i,function(login){
dwr.util.setValues({userId:userId, userName:login.userName,
passWord:login.passWord});
});
}
My js code for checkbox is
function Intialize(){
LoginManagement.getLoginDetails(function(loginList){
var x = "";
for(var i=0; i<loginList.length; i++){
var login =loginList[i];
x += "<tr><td>"+login.userId+"</td><td>"+login.userName+"</td><td>"+login.passWord+"</td><td><input type = 'checkbox' id = 'cbid"+login.userId+"'</td></tr>";
}
$("#loginTable").html(x);
});
}
How should i get the id value in edit so that if i click the button it should display the values corresponding. Any suggestion please?
Hope I understand you correctly.
Remove Edit() from onclick of edit link and continue the Initialize function as follows:
...
$("#loginTable").html(x);
ids = ['userId', 'userName', 'Password']; // Ids of text boxes to be populated
$("#editlink").click(function(){ // Assuming edit link has id="editlink"
var tds = $("#loginTable").find("input:checked[type=checkbox]").parent().siblings();
for(var i = 0; i < ids.length; i++){
$('#' + ids[i]).html($(tds[i]).html());
}
Edit(); // Better copy the code of Edit() directly in here
return false; // Prevent default click action (go to href)
});
});
If this is wrong please post the complete HTML as well.
the id can be retrieved by using the attr var idvalue = $("input:last").attr("id"); but you have to get reference to the checkbox in your scenario .. if you have a css class name associated with it use that like $(.classname) and then use the attr to get the value.
In my web application, I've set of checkboxes which on check populate a textbox above them.(If more than one checkbox is selected, then their values appear in the textbox separated by commas).
These set of checkboxes appear as rows in my HTML table.
Here's my HTML code.
<input type="text" id="newContactComment<%=rCount %>" name="newContactComment" size="45">
<input type="checkbox" id="commentText<%=rCount %>" name="commentText" value="<%=c.getComment_text() %>"
onclick="javascript:updateTextArea(<%=rCount%>);">
And the corresponding JS function is as follows:
function updateTextArea(rCount) {
var allVals = new Array();
$("#contactInfo input['commentText' + rCount]:checked").each(function() {
(allVals).push($(this).val());
});
$("#newContactComment" + rCount).val(allVals);
}
The rCount variable in the above function is the row # of my table.
Using this above, I'm not getting the expected behaviour..
For ex. If for row 1 of my table, I check chkbox 1 and 2, it correctly gets populated with values of those checkboxes. Now, for 2 of my table, I check only chkbox 3, it gets populated with the values 1,2 and 3 and not only 3 as I expect it to.
Any help will be greatly appreciated.
It would be better to use jQuery to set an event handler rather than setting it inline.
You want to use the onchange event not the onclick event.
If you add class names of checkboxes (or whatever you want) to the checkboxes the following will work:
$("input.checkboxes").change(function(){ //when checkbox is ticked or unticked
var par = $(this).closest("tr")[0];
var parID = par.id;
var patt1=/([0-9]+)$/g;
var rCount = parID.match(patt1); //Gets number off end of id
var allVals = new Array();
//Get all checkboxes in current row that are checked
$(par).find("td input.checkboxes:checked").each(function() {
allVals.push($(this).val());
});
$("#newContactComment" + rCount).val(allVals);
allVals = null; //empty array as not needed
});
I believe this or something along these lines will do what you want
You're trying to use the rCount variable from within the quoted string. Try this instead:
$("#contactInfo input['commentText" + rCount + "']:checked")