Hi I am trying to get the HTML of INPUT tag. But unable to..
<input type="checkbox" name="_QS4_CNA" id="_Q0_C7" class="mrMultiple" value="NA">
<label for="_Q0_C7">
<span class="mrMultipleText" style="">None of these</span>
</label>
</input>
And I am trying access as
var dat=$(':checkbox#_Q0_C7').html();
alert(dat);
But i cannot access this. Please help me on this..
The ".html()" method gets the contents of an element, and not the element itself. In your case, the problem is that your HTML is invalid. An <input> tag cannot have content. As far as the browser is concerned, the tag ends where the <label> tag starts, and the browser just ignores the closing tag.
Note that when you've got an "id" attribute to use to find an element, you don't need any other qualifiers in the selector (like ":checkbox"). Just "#_Q0_C7" is all you need, because "id" values have to be unique anyway.
edit — Note that if all you want is to get some attribute (like the value or the "checked" status) from the element, you can certainly do that:
var $cb = $('#_Q0_C7');
var isChecked = !!$cb.prop('checked'); // force a real boolean value
var value = $cb.val();
You can try accessing the RAW underlying DOM element and use its innerHTML property.
var dat = $(":checkbox#_Q0_C7")[0].innerHTML;
But like mentioned by Pointy, that might still get you nothing. Not sure what (if any) input elements have actual siblings.
Related
I recently saw a code voucher that surprised me a bit and I would really like to understand. Can the document.querySelector() take a parameter, an attribute to make selections :
const tabs = document.querySelectorAll('[data-tab-value]')
<span data-tab-value="#tab_1">Tab-1</span>
I would also like to know why the attribute name is enclosed in brackets.
document.querySelector is just like CSS selectors
It can even select elements with attributes like:
document.querySelector("input[name]") // <input name>; input which has attribute name
document.querySelector("input[type=number]") // <input type='number'>; input whose attribute type's value is number
I need to define a specific check box and (later on) click on it to complete the account creation. The problem is that part of the input id is dynamic and changes with each run. Therefore, my approach below is not working:
var nativeChannels = element(by.css("label[for='dp-native-9597']"));
When I inspect the element, it displays the following:
div class="switch"input id="dp-native-9597" type="checkbox" ng-model="controls.allNativeChannels" class="cmn-toggle cmn-toggle-round ng-pristine ng-untouched ng-valid" autocomplete="off">label for="dp-native-9597">/label/div
label for="dp-native-9597"/label
I searched for a way to put a wild character after dp-native- but looks like this is not allowed. Is there any way to define this type of check box, so that I could move on with tests?
Thank you for your help in advance!
Try using the below xpath.
.//label [contains(#for,"dp-native-")]
There are wild card selectors in CSS (http://www.w3schools.com/cssref/css_selectors.asp) :
[attribute^=value] a[href^="https"] Selects every <a> element whose href attribute value begins with "https"
[attribute$=value] a[href$=".pdf"] Selects every <a> element whose href attribute value ends with ".pdf"
[attribute*=value] a[href*="w3schools"] Selects every <a> element whose href attribute value contains the substring "w3schools"
Try one of these. I think you might search like this:
$(".switch[id*='dp-native'] label")
or by model (http://www.protractortest.org/#/api?view=ProtractorBy.prototype.model) :
element(by.model('controls.allNativeChannels')).$('label');
I am cloning some form elements and want to generate for them dynamic ids so I can acces their content later on, but I don't really know how to do that, I'm a noob with Jquery/Javascript, by the way.
My html:
<tr>
<td>
<label for="ability">Ability</label><br>
<div id="rank_ability" name="rank_ability">
<select name="ability" id="ability">
<option value=""></option>
<option value="hexa">Test</option>
</select><br>
<label for="range_ability_min">Range:</label>
<input type="textbox" name="range_ability_min" id="range_ability_min" class="small_text" value="0" /> -
<input type="textbox" mame="range_ability_max" id="range_ability_max" class="small_text" value="0" /><br>
</div>
Add Ability<br><br>
</td>
</tr>
My JS:
$(document).ready(function () {
var element, ele_nr, new_id;
$('.rank_clone').click( function() {
element = $(this).prev();
ele_nr = $('div[name="'+element.attr('name')+'"]').length;
new_id = element.attr('name') + ele_nr;
element.clone().attr('id', new_id).attr('name', new_id).insertAfter(element);
});
});
I setup a jsfiddle with what I got here: http://jsfiddle.net/xjoo4q96/
Now, I am using .prev() to select the element to clone which leads to those repeated 1 in the id/name attributes, how could I select it in another way (to mention: I really need to use 'this' because I need this little script in like 3 places, so I don't want to write it for an element with a specific id/class).
Also, I am counting only the element with the base name attribute so .lenght yelds 1 all the time, how would I go around counting all of them ? I guess I have to place them in another div or something but I don't know how would I go around couting them even then.
And, at last, how would I go around changing all the name/id attributes of the elements I have in the div ?
I'd appreciate any help. Thanks.
you can put the template in a hidden div like #tmpl, then clone and set the id attr, e.g.
$('#tmpl').children().first().clone().appendTo('#target').attr('id', 'the_generated_id');
Update
Demo of the template way: http://jsfiddle.net/xjoo4q96/1/, though it would be quite easy to adjust the code to clone the first component that already existed.
BTW, principally, id should be unique, thus the sub-element in the cloned component should use other attribute, like class or certain data- attribute, like those used in the updated fiddle.
Also you might want to call event.preventDefault() as you're clicking an <a>
You are searching already with the wrong name, since it still has the number attached. So delete it first, search for element which have a name attribute starting with this name and then use this base name to create a new one.
$(document).ready(function () {
var element, ele_nr, new_id, base_name;
$('.rank_clone').click( function() {
element = $(this).prev();
base_name = element.attr('name').replace(/[0-9]/g, '');
ele_nr = $('div[name^="'+base_name+'"]').length;
new_id = base_name + ele_nr;
element.clone().attr('id', new_id).attr('name', new_id).insertAfter(element);
});
});
And to answer your last question: you can not go around changing all ids of inner elements, it would be invalid HTML. In principal you can do the same with every id, like adding a number. If you have to do the same with all the name attributes depends on what you want to do exactly. If you have to distinguish between the first and second input, which I suggest, you have to change them too.
try to use cloneJs, it's clone ids, names input, and parametre inside functions ids of input must be like id_foo_1, id_foo_2 ,,,, and name be like inputName[0][foo], inputName[1][foo] https://github.com/yagami271/clonejs
I have a javascript program to filter a list of things in a HTML select control by typing a regular expression into an input (text) box. I can do the following to correctly filter a specific select control:
$(function() {
$('input[data-filterable]').keyup(
function() {
filter = new filterlist(document.myform.myselect);
filter.set(this.value);
});
});
but I have used a custom attribute (something one can now do in HTML5) called data-filterable. The attribute will store the name of the select control that is to be filtered so that JS can use the name of the control to filter the list. This would be a good idea because I will have a general function to filter any select box rather than a specific one.
Any ideas how I do this? I need something like this in the HTML:
<input data-filterable='{"to":"#selectbox1"}' size="30" type="text" />
but I'm not sure exactly what I'm doing here and what to do with the JS.
Thanks guys :).
Try this:
<input data-filterable="#selectbox1" size="30" type="text" />
$(function() {
$('input[data-filterable]').keyup(
function() {
filter = new filterlist($($(this).data('filterable'))[0]);
filter.set(this.value);
});
});
To break down the expression $($(this).data('filterable'))[0]:
$(this) wraps this in a jQuery wrapper. In our context, since it's a jQuery keyup event handler, this references the <input> DOM node.
$(this).data('filterable') retrieves the contents of the data-filterable attribute as a string. In our case, it's #selectbox1.
After that this string gets passed in to jQuery as a selector: $($(this).data('filterable')).
Finally, we take the 0'th element of the returned array which should be the DOM element of the target selectbox. Of course, if there isn't a selectbox which fits the selector this will fail rather miserably. If you suspect that this is a real scenario, check the .length of the returned array first.
I gather from this post that almost always one wants to be accessing the DOM property, not the HTML attribute.
So what are the rare useful exceptions? In what situation is accessing the HTML attribute better than accessing the DOM property?
Sometimes the attribute doesn't map to changes in the property.
One example is the checked attribute/property of a checkbox.
DEMO: http://jsfiddle.net/mxzL2/
<input type="checkbox" checked="checked"> change me
document.getElementsByTagName('input')[0].onchange = function() {
alert('attribute: ' + this.getAttribute('checked') + '\n' +
'property: ' + this.checked);
};
...whereas an ID attribute/property will stay in sync:
DEMO: http://jsfiddle.net/mxzL2/1/
<input type="checkbox" checked="checked" id="the_checkbox"> change me
var i = 0;
document.getElementsByTagName('input')[0].onchange = function() {
this.id += ++i;
alert('attribute: ' + this.getAttribute('id') + '\n' +
'property: ' + this.id);
};
And custom properties generally don't map at all. In those cases, you'll need to get the attribute.
Perhaps a potentially more useful case would be a text input.
<input type="text" value="original">
...where the attribute doesn't change with changes from the DOM or the user.
As noted by #Matt McDonald, there are DOM properties that will give you the initial value that would reflect the original attribute value.
HTMLInputElement.defaultChecked
HTMLInputElement.defaultValue
A rare exception is the case of attributes of a <form> element that could clash with elements in the form. For example, consider the following HTML:
<form id="theForm" method="post" action="save.php">
<input name="action" value="edit">
</form>
The problem is that any input within a form creates a property corresponding to the input's name in the form element, overriding any existing value for that property. So in this case, the action property of the form element is a reference to the <input> element with name action. If that input did not exist, the action property would instead refer to the action attribute and contain the string "save.php". Therefore for properties of form elements corresponding to attributes, such as action and method, it's safest to use getAttribute().
var form = document.getElementById("theForm");
// Alerts HTMLInputElement in most browsers
alert( form.action );
// Alerts "save.php"
alert( form.getAttribute("action") );
// Alerts "post" because no input with name "method" exists
alert( form.method );
This is unfortunate; it would have been better if this mapping did not exist, since the elements property of the form already contains all the form elements keyed by name. I think we have Netscape to thank for this one.
Live demo: http://jsfiddle.net/z6r2x/
Other occasions to use attributes:
When accessing custom attributes, such as <div mymadeupattr="cheese"></div>
When serializing the DOM and you want values from the original HTML for input attributes such as value and checked.
I can only come up with 2 more situations where accessing/setting attribute would have benefits
over property.
Style attribute:
In a case where you are not allowed to use any framework, you can use style attribute to set multiple styles at once like so:
elem.setAttribute( "style", "width:100px;height:100px;" );
instead of doing this:
elem.style.width = "100px";
elem.style.height = "100px";
or this:
var styles = {width: "100px", height: "100px"}, style;
for( style in styles ) {
elem.style[style] = styles[style];
}
Be aware that setting style attribute overwrites the previous one. And its probably better to write
a multiple style setter function anyway.
Href attribute:
A href attribute will usually contain a value like "/products", however the property will contain the resolved url, as in:
"http://www.domain.com/products" instead of what you really want: "/products". So if you wanna do something dynamically with
links, then reading the href attribute instead of property is better because it has the value you intended it to be.
Update
I suddenly found 2 more uses and I am sure there are more like this.
If you want to see if an element has custom tab index set, the easy way is to see if the element has the attribute. Since the default
value for .tabIndex-property depends on element and cannot be easily used to see if the element has custom tabIndex.
Seeing if element has a custom .maxLength property. This cannot be seen from property either:
document.createElement("input").maxLength
//524288
It is impossible to tell if the value 524288 was there intentionally without dealing with the attribute.