Get the parent row and find an element in JQuery - javascript

I have a checkbox in a column of an html table. When I check or uncheck it I want some text to be displayed/removed from a text area in the next column of the same row.
I did the following:
$(this).parent().parent().find('textarea').text = 'some text'
and also
$(this).parent().parent().find('textarea').val = 'some text'
but it does not work.
The html is like:
<tr>
<td>
<input type="checkbox" />
</td>
<td>
<textarea>
</td>
</tr>
I want to get the textarea of the same tr of the checkbox I check
UPDATE
I found that I should use .val("some text") but now the function is called only if I click the checkbox in the first row. Not for the rest

The issue is with how you are trying to set the value not how you are finding the element
try this
$(this).closest('tr').find('textarea').val("some text");
See here for more info .val()
UPDATE
an element ID has to be unique so you can't reuse the same one. Give all your checkboxes unique id's i.e "chkOne", "chkTwo" etc. Then use a class on all the checkboxes you wish to run this functionality from. i.e class="chkSelection". Then change your jQuery to look like this
$('.chkSelection').change(function() {
if($(this).is(':checked')){
$(this).closest('tr').find('textarea:first').text('Some text here');
}
});
This way all your checkboxes with a class of "chkSelection" when changed will run the functionality to find the next textarea and set the text.

Just give them identifiers, as surely you'll need to reference them somehow elsewhere (and if your structure changes it won't break as a side-effect) - note the use of val(), too:
<tr>
<td><input id="someName" type="checkbox"/></td>
<td><textarea id="someOther"></textarea></td>
</tr>
Then you can reference them explicitly:
$("#someName").change(function(e) {
$("#someOther").val("some value");
});
Keep it simple.

try this code
$("table input[type=checkbox]").change(function(){
// Your code.
});

Give generic classes to all the checkboxes and textareas... In the .change() function of the checkbox try using this: (Considering the class of the textarea is textarea)
$(this).parent().find('.textarea').html("Your text here");

To check if the checkbox is checked/unchecked, try attr('checked').. Also to get the values of all checked checkboxes, try 'input[type="checkbox"]:checked').val()

my solution
$('table input:checkbox').change(function(){
$(this).parent().next().find('textarea').val("some text");
});

If you want to be able to toggle the text on and off by checking/unchecking the box, something like this would work:
$("input[type=checkbox]").change(function() {
$(this).filter(":checked").parent().next().text('Text!");
$(this).not(":checked").parent().next().text('');
})
This would listen for any change to any checkbox on your page. When a checkbox changes, it will select the checkbox's parent's sibling (the next <td> element after the one surrounding the checkbox) and set its text to 'Text!' if the box is checked, or an empty string if the box is unchecked.
The benefit to using this method, aside from the text on/off functionality, is that you don't need to assign CSS classes/ids for it to work.

Related

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>

Selection from dropdownlist javascript event

I have this html part code :
<p><label>Taxe </label>
<select id="id_taxe" name="id_taxe" style="width: 100px;" onchange="taxselection(this);"></select>
<input id="taxe" name="taxe" class="fiche" width="150px" readonly="readonly" />%
</p>
Javascript method :
function taxselection(cat)
{
var tax = cat.value;
alert(tax);
$("#taxe").val(tax);
}
I'd like to set the value of taxe input to the selected value from the dropdownlist.It works fine only where the dropdownlist contains more than one element.
I try onselect instead of onchange but I get the same problem.
So How can I fix this issue when the list contains only one element?
This works:
$('#id_taxe').change(function(){
var thisVal = $(this).val();
var curVal = $('#taxe').val();
if(thisVal != curVal)
$('#taxe').val(thisVal);
$('#select option:selected').removeAttr('selected');
$(this).attr('selected','selected');
});
Use the change method which is very efficient for select boxes. Simply check the item selected isn't currently selected then if not, set the value of the input to the selected value. Lastly you want to remove any option's attr's that are "selected=selected" and set the current one to selected.
Just include this inside a $(document).ready() wrapper at the end of your HTML and the change event will be anchored to the select field.
Hope this helps.
http://jsbin.com/populo
Either always give an empty option, or in your code that outputs the select, check the amount of options, and set the input value straight away if there's only 1 option.
A select with just 1 option has no events, since the option will be selected by default, so there's no changes, and no events.
As DrunkWolf mentioned add an empty option always or you can try onblur or onclick event instead, depending on what you are actually trying to do.
Ok, just to stay close to your code, do it like this: http://jsfiddle.net/z2uao1un/1/
function taxselection(cat) {
var tax = cat.value;
alert(tax);
$("#taxe").val(tax);
}
taxselection(document.getElementById('id_taxe'));
This will call the function onload and get value of the element. You can additionally add an onchange eventhandler to the element. I highly recommend not doing that in the HTML! Good luck.

Update value of input after text

I want to add a default value to an input field on an existing form when the page is loaded. All of the inputs on the field have the same name and ID on this form.
<table>
<tr><td>Name:</td><td><input id="MultiLookupPicker" name="MultiLookupPicker"/></td></tr>
<tr><td>Company:</td><td><input id="MultiLookupPicker" name="MultiLookupPicker"/></td></tr>
<tr><td>Department: </td><td><input id="MultiLookupPicker" name="MultiLookupPicker"/></td></tr>
</table>
Here's the example http://jsfiddle.net/ljd144/6ocsLk6k/
How would I add a default value to the input immediately following the text "Company"? Thanks!
The input is not in your td so the find method won't work. You need to select the next td first.
$( "td:contains('Company')").next("td").find("input").val("test");
I updated your fiddle with the right selector
JSFiddle updated
You can't use the same id on multiple element, it's very very bad and will lead to unexpected result.
to add a default value, you can do it in html :
<tr><td>Name:</td><td><input id="MultiLookupPicker" value="yourvalue" name="MultiLookupPicker"/></td></tr>
or in jquery :
$("$MultiLookupPicker").val("yourvalue");
Try it ..but id must be unique
$( "td:contains('Company')").next().find("input").val("test");
NOTE: In your fiddle $( "td:contains('Company')").find("input") it always return empty array bcoz there is no input element that td , so use next() and find the input
updated fiddle

Selecting hidden form element by Id

I am trying to set a value to a hidden form element by selecting their Id and not their name attribute. The hidden element has id="user_lat and name="user_lat". How can I do that?
I seem to be able to select by name:
$("input[name='user_lat']").val(results[0].geometry.location.lat());
MY attempt at selecting by id below does not work:
$("input #user_lat").val(results[0].geometry.location.lat());
If the id is to be applied to the input, the selector can have no spaces:
$("input#user_lat").doSomething();
If you place a space between input and #user_lat, the selector attempts to match a child of the input, which doesn't make much sense. It would be like having the following markup:
<input><el id="user_lat" /></input>
Removing the space matches any input that contains the ID:
<input id="user_lat" />
You must stick them together "input#user_lat"
input #user_lat means:Look for an input and then find inside the element with id user_lat
You are close, take out "input" from the second statement and you should be good.
$("#user_lat").val(results[0].geometry.location.lat());
When you are usign the selector "input #user_lat" your saying the element "user_lat" inside an input. So what you need to do is just delete the space between them, something like this:
$("input#user_lat") ...

Jquery checkboxes within containing table selector question

My current code:
<script type="text/javascript">
function checkAll(checked) {
$("input[type='checkbox']:not([disabled='disabled'])").attr('checked', checked);
}
</script>
<input type="checkbox" id="cbxSelectAll" onclick="checkAll(this.checked);" />
The short version:
How do I modify the function call and method above to check all checkboxes inside a table containing the checxbox form element.
The long version:
I am creating a WebUserControl containing a grid view in asp.net that is going to have a delete option. I would like the delete to be a series of checkboxes with one a box in the header to select all of them. What this amounts to for non ASP.NET people is a table with a header row that has a checkbox and every row also has a checxbox.
I have used the above code to check all boxes on the entire page. That won't work here though because I want to have multiple of these on the page at once each working independently. I know I could use a selector to select all the boxes if I ID'd the table but that would require some coding to name the table uniquely and then put that name in the script block.
Really what I would like is to modify the script above to check all checkboxes in the containing table of the "select all" box. The table containing the checkbox could be nested within others but I don't see any being nested within it, or if there are and the nested table also contains checxboxes I don't care if they also get selected.
Thanks for your help.
First, don't mix your HTML and your Javascript. Use event handler binding instead.
Second, use closest to get the nearest ancestor element of a particular type:
$(document).ready(function(){
$('#cbxSelectAll').click(function() {
$(this)
.closest('table') // get the parent table element
.find("input:checkbox:enabled") // find children that match the selector
.attr('checked', this.checked); // set their checked value
});
});
Change your inline attribute to this:
<input type="checkbox" id="cbxSelectAll" onclick="checkAll.call(this);" />
And your checkAll() to this:
function checkAll() {
$(this).closest('table').find("input:checkbox:enabled").attr('checked', this.checked);
}
Using .call(), it is called from the context of the element clicked.
Then the jQuery gets the closest()(docs) <table> and finds the inputs using the checkbox-selector(docs) and the enabled-selector(docs) .
Then when using the attr()(docs) method, you can use this.checked to set the checkboxes to the current state of the one checked.
You can find the table containing the select all using .closest
function checkAll(checked) {
var $table = $(this).closest('table');
$table.find("input[type='checkbox']:not([disabled='disabled'])")
.attr('checked', checked);
}
If there might be several nested tables it's often easiest to specify the one you want with a class, e.g. $(this).closest('table.tableOfCheckboxes'); where you add class tableOfCheckboxes to the table you want to find.

Categories

Resources