How to get data element of checkbox on change event - javascript

I've got a dynamic table of items with checkboxes next to each item. When a user selects a checkbox I want to grab the "Name" item from the table and add it to a textbox. See image:
The way I'm trying to accomplish this is by adding a "change" event to every checkbox and populating it's "data-name" element with the name of the text.
<tbody>
#foreach (var item in Model.Items)
{
<tr>
<td><input type="checkbox" name="selectBox" data-name="#item.Name" /></td>
As you can see I'm populating data-name with the item name as a way to get around pulling it directly (which I don't know how to do). Now in javascript/jquery I'm tying an event to every checkbox and attempting to get the data element using the following code:
$('input[name=selectBox]').change(function (item) {
var text = $(item).attr('data-name');
});
When the code runs the event is firing for all checkboxes, but "text" is undefined when I expect it to be the name data.
Looking for an answer to my method of doing this AND/OR a better way involving skipping the data element all together and getting the name value directly. Thanks for looking.

Try this:
var text = $(this).data('name');
The first parameter of your change function is the event, not the element itself. Also, jQuery automatically sets the function scope (this) to the element being changed.
See Documentation

In your case item is event object not DomElement, you can get element through event property currentTarget
$('input[name=selectBox]').change(function (item) {
var text = $(item.currentTarget).attr('data-name');
});
or use this because this refer` on current Element, it is the same as in previous example but shorter
$('input[name=selectBox]').change(function (item) {
var text = $(this).attr('data-name');
});

Related

OnClick event is only getting the first dynamically created row/id

I have a table where if X has a value, display X, otherwise, add a link which when clicked will display a textbox where user can input the value. I dynamically assign IDs/classes to the link and textboxes but when I run the application, each click on any link only seems to trigger the first row. I put in alerts to show what row is being clicked and I always get the first row. Looking at the browser DOM explorer, I can see that each row has its own unique ID. How do I get each OnClick event to grab the correct corresponding ID?
C#/Razor code:
<td>
Unmapped
<input type ="submit" class="editAction hidden" value="#string.Format("tr{0}",i)" name="action:ChangeToEditSubAction" />
<input type="hidden" name="#Html.Raw("EntityMapping.EMREntityID")" value="#Html.Raw(Model.DisplayResults[i].EMREntityID)" />
<span class="#string.Format("tr{0}accountTxtBox",i) hidden">#Html.TextBoxFor(m => m.EntityMapping.AssignedHOAccountID)</span> </td>
Javascript Function
function UnmappedClick() {
//$(".accountTxtBox").removeClass("hidden");
//$(".unmapped").addClass("hidden");
//$("#btnSave").removeAttr('disabled');
//$(".editAction").click();
//$(".editAction").val(null);
alert($(".unmapped").attr('id'));
var txtBox = $(".editAction").val();
var actTextBox = "." + txtBox + "accountTxtBox";
$(actTextBox).removeClass("hidden");
alert(txtBox);
}
DOM Explorer Image
You can pass a parameter from your onclick event using the "this" keyword.
onclick="UnmappedClick(this.id)"
function UnmappedClick(id){
//now you have the specific ID
}
or if necessary pass the whole control over
onclick="UnmappedClick(this)"
you can try this
$(this).attr('id') // use this
instead of
$(".unmapped").attr('id')
This will give you the current elements id when you click
As you can see here, using $('.class') will return a list all the elements with that class. When you use $(".unmapped").attr('id') you'll always get the value of the first element in the list, that's why you always get the first row.
The same will happen with var txtBox = $(".editAction").val();. With $(actTextBox).removeClass("hidden"); you'll remove the class hidden from all the elements matched.
To get the id of an element you can use onclick="unmapped(this) or onclick="unmapped(this.id)" using the following code depending on the onclick attribute
function unmapped(element) {
var id = $(element).attr('id')
alert(id)
}
function unmapped(id) {
alert(id)
}
You can check this fiddle to see them in action.

How to select a specific <li> with jquery get the attr value of value and display it on the website

I have an assignment that goes as follows:
Create an event listener so when you click any list item the value of its "value" attribute will be displayed next to this line.
I have in my HTML and ordered list with 8 list items. value=1,2,3.. etc
Where im at now
$("li").click(function () {
var value = $("li").attr("value");
$("#spanFieldId").text(value);
});`
spandFieldId is where the list item value should print. At the moment it always print 1 whether i click the first list item, the second or any other.
So basicly, how do i get it to select the specific li (which i click on) with jquery take out the attr value of value and display it on the website? List item in html look like this
<li value="3">blablablabla</li>
<li value="4">blablablabla</li>
<li value="5">blablablabla</li>
Any suggestions out there?
Try this:
$("li").click(function () {
var value = $(this).attr("value");
$("#spanFieldId").text(value);
});
Replace
var value = $("li").attr("value");
with
var value = $(this).attr("value");
The string selector "li" selects all <li>s and the .attr() will only return the first value found in that selection. Using this instead takes advantage of the context that jQuery passes to listeners, which contains a reference to the DOM element the event is acting on.
Instead of
var value = $("li").attr("value");
use
var value = $(this).attr("value");
That will select the clicked list instead of the first one.

Using jQuery input event to conditionally update a <td> innerHTML

I'd like to do something that at least for me is complicated.
I have this in a much larger table:
<table><tr>
<td class="editC" id="comments:942" onchange="TimeLine();" onclick="empty('comments:942');" title="Click to edit..."> Second test of new comment behavior
</td></tr></table>
Here is what is going on:
1) class="editC" = I use Editable to edit and write to the DB.
2) id="comments:942" = the id value
3) onchange="TimeLine();" = The timeLine() function gets information from another DB and puts it into a second HTML table on screen. This works.. no worries.
4) onclick="empty('comments:942')" = empty is a function to empty the field but it does not update the DB. I just want a clean input field to enter new data in place of the existing data.
What I'd like to happen is this.
a) If something is typed into this now empty field, all is good, my save.php code will save it to the DB. This works great.
b) But if nothing is typed into the now empty field, I want the old value put back in place without updating the DB. In my head this would be equivalent to first having cut the current value then pasting it back if nothing new had been typed.
It seems to me that jQuery should be able to do this with the input event.
function empty(thisID){
$(thisID).on('input',function(){
$(this).val() // should get current value
});
document.getElementById(thisID).innerHTML = ''; // empty the field
... but now what? How do I determine if a change was made? How do I replace the original value if a change wasn't made?
}
But now what? How do I determine if a change was made? How do I replace the original value if a change wasn't made?
td elements do not have an input event. It is however possible to nest an <input> tag inside a td.
$("td input").on("focusin", function() {
currentValue = $(this).prop("value");
$(this).prop("value", "");
}).on("focusout", function() {
if($(this).prop("value") === "") {
$(this).prop("value", currentValue);
}
});
Here, when the input is clicked, found using the focusin event, the value of the input is stored in a global variable. It needs to be global, because we have to use this variable in the next function. After the variable is stored, the input field is erased, by setting the value attribute to an empty string.
If the user didn't make any changes and leaves the input field, detected with the focusout event, the value attribute will be reset to what it once was.
Current Fiddle
http://jsfiddle.net/a592awoo/1/
One problem is you are passing in 'comments:942' to your empty function.
So when you do $(thisID) it is trying to find an element <comments:942>. To select by an id you need a #.
You could do this:
$('#'+thisID)
Or simply pass in '#comments:942'.
However, that won't work either. Using a : in an id is typically a bad idea, as it has a special meaning in CSS and jQuery selectors, so you may want to use a - instead. If that's not an option, you can escape the :.
Even with the jQuery selector fixed, I'm not sure how you are trying to get user input on a <td> element. You need an <input> element.
I believe you are trying to accomplish something like this:
$(document).ready(function() {
//this will add a click function to all elements with a class of 'editC'
$('.editC').on('click', function() {
//clear the current value
$(this).empty();
//append an input element
$(this).append($('<input type="text" placeholder="Enter new value">'));
//append a button
var btn = $('<button>Submit</button>');
//add click function on submit button to replace old td value with what is in the input
$(btn).on('click', function() {
//get the parent <td> element
var td = $(this).parent();
//get the previous element's value (the value of the <input> element)
var val = $(this).prev().val();
//remove the input element and button from the td
$(td).empty();
//set the text of the <td> to what was entered in the input element
$(td).text(val);
});
$(this).append(btn);
//unbind the click event, so that it does not perform this function when you click in the input element
$(this).unbind('click');
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<table>
<tr>
<td class='editC' id='comments-1'>Value 1</td>
<td class='editC' id='comments-2'>Value 2</td>
</tr>
</table>

Event handler with AjaxChosen

I'm trying to use this jquery plugin: https://github.com/meltingice/ajax-chosen
I have a multiple select and I would like to know which event is called when someone deletes a value or when someone choses a value.
Here's what I've done:
$("#firmsSelect").ajaxChosen({.....}).change( function (event) {
console.log($(event.currentTarget));
})
I would like to know what can I do whith the currentTarget object. (I tried .val() but the valueI get is for the entire select , aka an array, whereas I just want the value of the element that was deleted/selected.
I had the same problem. First I solved it with something like the following code:
$("#mySelect").chosen().change(function (event, params) {
//...
})
then you can use:
var selectedValue = params.selected;
But this does not solve everything, for example when you deselect then property selected is undefined, so you can't get the value of the item that has just been deselected.
Eventually I used something like:
var options = $(evt.currentTarget).find('option');
The array "options" contains all your <options> tags within the <select> tag. You can then iterate over the items and, with some bookkeeping, know the item that has been deselected.
I hope this helps.

Adding an item to an editable menulist when it is typed in by the user

I am creating a menulist popup list dynamically. I the editable and open attributes to true. What I would like to be able to do is to be able to add a new menulist item when the user types in an item that is not already present. Is this possible? If so, how?
I am creating the list like so:
var ml = document.createElement("menulist");
ml.setAttribute("editable","true");
ml.setAttribute("open","true");
ml.setAttribute("oncommand","alert(this.value)");
var mp = document.createElement("menupopup");
var mi = document.createElement("menuitem");
mi.setAttribute("label","item1");
mi.setAttribute("value","1");
mp.appendChild(mi);
//add as many items as i feel
ml.appendChild(mp);
When the value is changed, the alert function is fired when the item is changed but when I type in anything, it is not fired. Basically, I want to eventually pass the value to a funcntion I call from here to add the item to the list.
First of all, you should seriously consider using addEventListener instead of changing attributes like oncommand:
ml.addEventListener("command", function(event) {
alert(this.value);
}, false);
If you want to be notified about changes in the text field then you should add an event listener to the text field:
ml.appendChild(mp);
ml.inputField.addEventListener("input", function(event)
{
alert("Text field value changed");
}, false);
Note that this has to be done after the element is added to the document, before that the inputField property will not be defined (corresponding XBL binding didn't apply yet).
For reference: menulist.inputField, input event

Categories

Resources