Get closest parent with stated attribute? - javascript

I have the following code :
<input pid="hidVoteKey" type="hidden" value="0" />
<ul id="mainPostList" class="verticalList">
#foreach (var postViewModel in Model.Posts)
{
<li><div class="voteCon">...</div></li>
}
</ul>
Then I have a jquery that loop all elements with class voteCon and then try to get the parent input like this :
$(".voteCon").each(function () {
InitVoteControl($(this), $(this).parent("input[pid='hidVoteKey']").val());
});
The problem is that it will not find the hiddenfield?
In this case the voteCon contains up/down buttons and there is some javascript functions bound here to make ajax calls. There will be multiple lists like the one above on the same page but thay all will have diffrent hidVoteKey.

It won't find the <input> because it isn't a parent (or ancestor) of the <div class="voteCon">. It's on the same level as (a sibling of) the <ul>, which is an ancestor of the <div>. You could do this:
$(this).closest('ul').prev('input[pid="hidVoteKey"]').val()

Just use then not type hidden , you can use inline style="display:none;"

Related

JQuery: dynamically update HTML so that it is recognized by JQuery

So, first of all, I am a newbie in Web (html/js)
What I want to achieve:
I have a custom tree and I want to be able to dynamically (using jquery) create children for that tree:
Html:
<ul>
<li>
Item
<input type="button" value="+" class="childAdder">
<ul class="childrenList"></ul>
</li>
</ul>
JS:
$(".childAdder").click(function() { // add child which is the same as root
$(this).parent().children(".childrenList").append(
'<li>Item</li>\
<input type="button" value="+" class="childAdder">\
<ul class="childrenList"></ul>'
);
});
And as you can see, I know how to add a child (more or less, an advice is always welcomed). The problem is, however, that this code only works for items that are "predefined" in html --> everytime I dynamically(via JS) add a child, this code just does not execute for this newly created element (tried to do alert('Hello'); - nothing is seen)
Question:
I assume I need to somehow "properly" add my new child to the DOM(?) of HTML or whatever, so that it is then recognized by JS, right? (but that seems to be only achieved trough HTML static page, no?)
Anyway, how do I make this thing work: add new child so that the same JS code that is executed for HTML element is executed for the element created by JS
is there a solution or the whole implementation is just wrong?
You need to use event delegation for this to work. This is done by using the on JQuery method for event wiring and modifying the parameters.
Also (FYI), a <ul> element can only contain <li> elements as children. Your bullet/nested list structure is invalid.
Lastly, in the HTML string you were appending included random \ characters, which are not needed and are actually invalid at those locations.
Here's the correct implementation with the HTML corrected to be valid.
// JQuery event delegation requires the use of the "on" method and then you
// bind the event to an object that is sure to always recieve the event (document
// works well here because of event bubbling). Then you specify the target element
// that the actual event will be triggered from.
$(document).on("click", ".childAdder" ,function() {
// add child which is the same as root
$(this).parent().children(".childrenList").append("<li>Item<br><input type='button' value='+' class='childAdder'><ul class='childrenList'></ul></li>");
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<ul>
<!-- <ul> and <ol> elements can only have <li> elements as thier children (aside from
comments like this one). To properly nest lists, organize the HTML as follows: -->
<li>Item<br>
<input type="button" value="+" class="childAdder">
<ul class="childrenList"></ul>
</li>
</ul>

Finding correct SPAN tag using jQuery prev() and next()

Hey all I am needing the following html code to get the value of "deliver best smile" which seems to be 6 prev() and 2 Next().
<div id="eea305a4-32b2-434d-8623-4dc3e2fcf119F_SelectMany" class="lfFormField
lfFormFieldSelectMany F_Form1-P_NewPage-F_SelectMany">
<div class="">
<fieldset class="composite-field-fieldset">
<legend class="no-form-field-mandatory-sign-css">
<span id="F_SelectMany-required"
class="form-field-mandatory-sign-css lfFormFieldRequiredMarker no-form-field-mandatory-sign-css">*</span>
<span class="form-field-title-sign-css lfFormLabel">deliver best smile</span>
</legend>
<div style="padding=left:0.1em"
dojoattachevent="onmouseover:onMouseOver, onclick:onClick, onmouseout:onMouseOut"
class="dojoDndHandle freedom-base-mixin-css"
id="eea305a4-32b2-434d-8623-4dc3e2fcf119F_SelectMany-widget"
widgetid="eea305a4-32b2-434d-8623-4dc3e2fcf119F_SelectMany-widget">
<ul id="e2b7488e-a88c-4da0-8287-4f8e4e6091f4tbl"
dojoattachpoint="containerNode,focusNode"
class="selection-group">
<li dojoattachpoint="listItem"
class="vertical-selection-group-item"
id="freedom_widget_solution_form_FreedomOptionButton_0"
value="0" type="checkbox"
widgetid="freedom_widget_solution_form_FreedomOptionButton_0">
<div class="selection-group-item-container notDojoDndHandle">
<span dojoattachevent="onmouseover:onMouseOver, onclick:onClick, onmouseout:onMouseOut"
class="selection-group-item-input dijitInline freedom-base-mixin-css freedom-base-mixin-cssChecked dijitChecked"
widgetid="2ff949f4-c88e-4769-8e36-23c81661af92-btn">
<input dojoattachpoint="textbox,focusNode,_aroundNode"
id="2ff949f4-c88e-4769-8e36-23c81661af92-btn"
class="dijitReset dijitCheckBox notDojoDndHandle"
type="checkbox" tabindex="0"
dojoattachevent="onclick:_onClick"
role="checkbox" aria-checked="true"
name="group_eea305a4-32b2-434d-8623-4dc3e2fcf119F_SelectMany-widget"
value="Achieve and maintain quality"
style="-webkit-user-select: none;">
</span>
<div class="selection-group-item-text-container dijitInline">
<label dojoattachpoint="titleNode"
for="2ff949f4-c88e-4769-8e36-23c81661af92-btn"
class="selection-group-item-text bold-selection-group-item">Achieve and maintain quality</label>
</div>
</div>
</li>
My position at that time is at the Achieve and maintain quality value from the input tag.
Currently I tried the following:
if ($(this).is(":checked")) {
var testing = $(this).prev().prev().prev().prev().prev().prev().next().next().html();
console.log(testing);
loop++;
}
The var testing is what I am trying to get that value from but it comes up with "undefined" so I am guessing I am not stopping at the correct spot?
Any help would be great!
You could try traversing up to the parent container and then doing a find on that element by it's class.
For example:
Traverse to parent by id:
$(this).closest('#eea305a4-32b2-434d-8623-4dc3e2fcf119F_SelectMany').find('.form-field-title-sign-css');
Traverse to parent by class:
$(this).closest('.lfFormField').find('.form-field-title-sign-css');
Or travers to parent by HTML element:
$(this).closest('fieldset').find('.form-field-title-sign-css');
And to get the value, in this case you would probably want to do .text() instead of .html(). Unless of course you actually want all the HTML.
And finally, if this id F_SelectMany-required isn't random. You could do this instead. Which should help it be a bit more specific.
$(this).closest('.lfFormField').find('#F_SelectMany-required').children('.form-field-title-sign-css');
Check this code
$(function(){
var $lbl=$("label[dojoattachpoint='titleNode']"); //Your position
$lbl.click(function(){
if (!$("#" + $(this).attr("for")).is(":checked")) {
var $fieldset=$(this).closest("fieldset");
alert($("legend",$fieldset).find("span").text());
}
})
})
Jquery's prev() gives you the previous sibling. In the DOM of the document you are posting, the input with "Achieve and maintain quality" in the value, does not have any siblings. It is the only child of the span that surrounds it, so you are going to get undefined no matter what combination of prev() and next() you do. Did you mean to use parent() instead of prev()?
But much better to give that span an id
deliver best smile
and get to it by using $("#SmileSpanId")

How is this selector working?

In the HTML I have the following element:
HTML
<input id="userNameTxt" type="text" class="input" value='ABC>
And i am selecting it like this in jQuery:
APP.js
$(userNameTxt).val()
What is this selector selecting? (Like when I use $('.something') -> it's selecting the Class of the element or $('#something') it's selecting the ID.)
It seems to be selecting the ID, but then is it similar to the # selector? If so then when to use such selector?
It is because the browser feature which will create global variables with element id properties.
If you use console.log(userNameTxt) you will be able to see the element get logged, so in your case you are passing a dom element reference to jQuery which is a valid param.
console.log(userNameTxt);
console.log(somename);
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<input id="userNameTxt" type="text" class="input" value='ABC' />
<div id="somename"></div>
HTML Standard
DOM Element References as Global Variables
Do DOM tree elements with ids become global variables?

How to remove all elements in a div after a certain div

So I have a div that is drawing in dynamic elements at its bottom and I want to hide these elements, no matter what their IDs are using javaScript/jQuery. Basically my HTML looks like this:
<div class="right-panel">
<div class="info">Text</div>
<form id="the-form">
<input type="hidden" name="first-name" value="">
<input type="hidden" name="last-name" value="">
<input type="hidden" name="state" value="">
</form>
<script>javaScript</script>
<div id="dynamic-id-1">Advertisement 1</div>
<div id="dynamic-id-2">Advertisement 2</div>
</div>
I'd like to ensure that the "dynamic-id-1" and "dynamic-id-2" divs are always removed or hidden no matter what their ID's are (their IDs are subject to change). How do I target these elements without targeting their IDs?
Edit--I tried this, but my approach seems limited, and I couldn't get it to work with multiple divs, even when chaining:
$('#the-form').next().hide();
(Note: unfortunately they don't have a class, there are multiple divs, and the IDs are always completely different. I was hoping there might be novel way to target the last two divs of the wrapping div and hide them)
If the script tag is always before the div's that need removing you could do this -
$('.right-panel > script').nextAll('div').remove();
http://jsfiddle.net/w6d8K/1/
Based on what you tried you could do this -
$('#the-form').nextAll('div').hide();
http://jsfiddle.net/w6d8K/2/
Here are the docs for nextAll() - https://api.jquery.com/nextAll/
The simplest route would be to add classes to the dynamic elements. Something like:
<div class="removable-element" id="dynamic-id-1">Advertisement 1</div>
Then, you can do something like:
$(".right-panel .removable-element").remove()
If only one div at a time is generated dynamically. Add this to dynamic generation:
$('#the-form + div').hide();
Another method to achieve the same (not preferred) is:
$('#the-form').next('div').remove();
You are saying you don't want to target their "id", but is there some specific part in the id that will remain the same ?
like for instance "dynamic-id-" ?
If this is the case you can target them by using a "like selector". The code below would target all divs whose ID is starting with "dynamic-id"
$('div[id^=dynamic-id]').each(function () {
//do something here
});
Target the class instead of the dynamic ID.
<div class="element-to-remove" id="dynamic-id-1" />
<div class="element-to-remove" id="dynamic-id-2" />
$('.right-panel . element-to-remove').remove();

jQuery update form element

I have a form that I create a checkbox on a click of a button. I am using https://github.com/pixelmatrix/uniform which provides an update function to style dynamically create elements which does not work. I got a work around but my problem is that it also reset the already created elements so they double, triple etc.
They are wrapped in a div with a class of checker. Is there a way to check if the div is around it first before applying my $('.table').find('input:checkbox').uniform(). I have tried different examples but they dont seem to work with my code and my jQuery is still limit.
Thanks
<div class="checker" id="uniform-160">
<span>
<input type="checkbox" name="chbox" id="160" style="opacity: 0;">
</span>
</div>
jQuery:
$(".fg-button").live("click", function(){
$('.table').find('input:checkbox').uniform()
});
Try this:
$('.table input:checkbox').not('div.checker input').uniform()

Categories