Using jQuery, I am copying a select into a ul for use in a mobile app. Some of the values in the select options have leading 0s. I'm using a custom attribute in the li elements to mimick the values in the select's options.
When I copy the value into the li:value, it loses the leading 0. I've even tried creating the whole li as a liter string that I append to the outer ul.
html:
<select id="seltest">
<option value="011111">good bye</option>
</select>
<div id="container"></div>
javascript:
$("#container").append("<ul id='thefilter'></ul>");
$("#seltest option").each(function () {
var optval = $(this).val();
var strvar = '<li value=\"' + String(optval) + '\">' + $(this).text() + '</li>';
alert(strvar);
$("#thefilter").append(strvar);
var lastli = $("#thefilter li:last");
alert(lastli[0].outerHTML); // now the value has lost the leading 0
});
Here's a fiddle to show an example: http://jsfiddle.net/richbuff/4RbH9/7/
Does anyone have an idea how to preserve the leading 0? It seems like jQuery is modifying my text.
TIA!
The browser is actually enforcing the spec. From the Mozilla Developer Network:
The only allowed value for this attribute is a number, even if the list is displayed with Roman numerals or letters.
In my handful of years of web development I've never used the value attribute on a list item. So, some of you might find this additional note of interest:
This attribute was deprecated in HTML4, but reintroduced in HTML5.
I'm using a custom attribute in the li elements
No, you aren't. There is a standard value attribute for LI elements.
I don't think this has anything to do with jQuery (other than it creates confusion between DOM properties and HTML attributes). In the following:
<ol>
<li value="06" onclick="alert(this.value)">Show value property
<li value="06" onclick="alert(this.getAttribute('value'))">Show value attribute
</ol>
both IE and Firefox return 6 for both alerts. The only difference is that in the first case, the value is type number and in the second type string (since getAttribute returns a string).
If you want to preserve the literal value, use a data- attribute on the LI.
Related
I am not able to select checkbox which has id="check stage<lead>" in jQuery Selector.
HTML:
<input id="check stage<lead>" type="checkbox" title="Select/Unselect Column" name="chk-stage-column-select" value="" onchange="">
Javascript:
// escape jquery selectors
function jQueryEscape(str) {
if (str)
return str.replace(/([ #;?%&,.+*<>~\':"!^$[\]()=>|\/#])/g, '\\$1');
return str;
}
var StageName = "<lead>";
$("[id='check stage" + jQueryEscape(StageName) + "']").prop("checked", true);
Equivalent JsFiddle : https://jsfiddle.net/vuw43uav/5/
Note: I'm using jQuery 1.7 and we can select id with spaces in jQuery. refer this jsFiddle: https://jsfiddle.net/vuw43uav/7/
I know you asked to make it work using jQuery Selector, but you can do it using javascript.
Just select the element using javascript and make it checked.
document.getElementById("check stage"+StageName).checked = true;
Here is the working fiddle for your 1.7 jquery version.
Fiddle
In case you want jquery selector, just select the element using javascript and then convert it to jquery selector, I know this is lame but should work fine for you.
var y = $(document.getElementById("check stage"+StageName));
y.prop("checked",true);
Id attribute must not have any space characters, check this spec
The value must be unique amongst all the IDs in the element's home
subtree and must contain at least one character. The value must not
contain any space characters.
There are no other restrictions on what form an ID can take; in
particular, IDs can consist of just digits, start with a digit, start
with an underscore, consist of just punctuation, etc.
use data-id instead
<input data-id="check stage<lead>" type="checkbox" title="Select/Unselect Column" name="chk-stage-column-select" value="" onchange="">
$("[data-id='check stage" + StageName + "']").prop("checked", true);
Demo
I'm working with the following bit of html and am trying to select it's value in either plain javascript or jquery. The name attribute can vary so I can't use it as my selector, although it will always represent the same data (grade_level). I think my best way of selecting it is via the string 'students.grade_level, but I'm not sure how to access it.
<input type="hidden" name="UF-001008-1$formatnumeric=#########.#####" value="1" data-validation="{"maxlength":"10","isinteger":"true","type":"number","key":"students.grade_level"}">
I have so far not been able to select element's value. I have tried:
var myvar = $( "input[data-validation~='students.grade_level']" ).val();
var myvar = $( "input:contains('students.grade_level')" ).val();
How else can I go about this?
TYIA
The way that you have given your attribute is wrong,
<input type="hidden" name="UF-001008-1$formatnumeric=#########.#####" value="1" data-validation="{'maxlength':'10','isinteger':'true','type':'number','key':'students.grade_level'}">
Use quotes properly to cover your attributes, either escape the double quote or use single quotes instead.
And after correcting that you could use the *= attibute value contains selector to achieve what you want,
var myvar = $( "input[data-validation*='students.grade_level']" ).val();
:contains() selector will not work out since it would search for matching text content. Also ~= attribute contains word selector wont work out as we do not have any word in our data-validation attribute. Word in the sense, group of texts separated by a space.
DEMO
So I've seen several posts explaining how to use a variable in a value for attribute selection. i.e. (where the JS event refers to the div (making it $(this):
HTML
<div id="item1"></div>
<div id="item1" style="display: none;"></div>
JS
var find = $(this).attr("id")
$('div[id="'+find+'"]').show();
But I would like to know how to use a variable in a jquery selector to find something with a similar string to the value of the variable. i.e. finding an element from the example above but looking for "#item1div", where the event target is still "#item1"
HTML
<div id="item1"></div>
<div id="item1div" style="display: none;"></div>
JS
var find = $(this).attr("id")
$('div[id="'+find+"div"'"]').show(); // incorrect syntax
So my question is: How do I correct the above syntax to include an additional string in the attribute check?
I can't find any reference to the correct syntax for how to add compile a string of the value of a variable and an explicit string then check that as the value for x attribute.
I know I can use [id*="'+find+'"] here because the alternate id contains the same characters as the basic one, but I want to know how to target a specific other id based on the first one. For example if I had #item1, #item1div, and #item1img, how can I use an event on "#item1" to find attribute values equal to "item1div" and/or "item1img"
EDIT: I also just realized I can just use [id|="'+find+'"] if I name the divs accordingly with hyphens, but again doesn't solve ids with different endings (or different strings that come after the hyphen)
$('div[id="'+find+"div"'"]') isn't valid Javascript syntax:
$( // jQuery function
'div[id="' // String
+ find // Add variable
+ "div" // Add String
'"]' // Unexpected string! - Error
One example of valid syntax would be:
$('div[id="'+find+'div"]')
However, since it's an id, you can use the id selector instead:
$('div#'+find+'div')
the question is very unclear, but I assume your question boils down to :
Q:how do you search all the elements where it starts with string x ?
A:To get all the elements starting with "item1" you should use:
$("[id^=item1]")
You should use ID selector like below to find an element by ID,
$('#' + find).show();
To find item1div or the dynamic first part - $('#' + find + 'div')
Note: the incorrect syntax you had mentioned is because of a missing + - It should be
// V-- you missed this
$('div[id="'+find+"div"+'"]').show();
To add the explicit string to the attr value you can write as follows
$('[attr="'+attrVal+'extraString"]')
For evample in case of id of div itemdiv
var item1ID = $('#item1').attr('id'); // item1
$('[id="'+item1ID+'div"]') // valid selector to select #item1div
This question already has answers here:
Getting an option text/value with JavaScript
(4 answers)
Closed 8 years ago.
I have this code, with books of the bible all within a element:
<option value="1">Genesis</option>
<option value="2">Exodus</option>
<option value="3">Leviticus</option>
<option value="4">Numbers</option>
<option value="5">Deuteronomy</option>
<option value="6">Joshua</option>
<option value="7">Judges</option>
To further explain, I have the value as the book ID, so when I go to fetch all the verses from my Database I can just refer to them by the book number.
But doing that, I have no way of getting the user viewed friendly name like "Genesis", so that I can format it like that.
How do I fetch this (the one currently selected, i.e. "Genesis" not '1') from JavaScript?
Save the result of your getElementById to a variable like sel, and then do this:
var text = sel.options[sel.selectedIndex].text;
Select elements have an .options property that gives you an array-like collection of all of its nested option elements. They also have a .selectedIndex property, which returns the index of the currently selected element.
Using the two of these, you can get the currently selected option. Then simply use .text to get the text content of the selected option.
If you don't need to support IE6/7, you can use document.querySelector() to make things a little shorter.
var text = document.querySelector("#the_select_id option:selected").text;
The querySelector() method returns a single element, or null if none was found. There's also a querySelectorAll() method that will return a collection of elements, useful for when your selector should match multiple elements.
If your parent element has name="books" as an attribute, and is a select element, then you can do this using jQuery:
var bookName = $('select[name="books"] option:selected').text();
If your parent element has an id="books" as an attribute, and is a select element, then you can do this using plain JavaScript (can probably be improved upon):
var books = document.getElementById('books');
var bookName = books.options[books.selectedIndex].text;
This is heavily trimmed down source code from a webpage I'm working on right now.
<!--// GRID ENTRY //-->
<li class="entry" id="sjDDulC8wt">
<div class="entry_actions">
<ul class="entry_actions">
<li class='have_it'>
<a href='javascript: haveItem("name", "id", "none")' target='_self' title='Have It' class='have_it'>%</a></li>
</ul>
</div>
</li>
Inside the haveItem() function I'm trying to change the class of the <a> element from 'have_it' to 'have_it selected' to change the appearance of the element. The reason for the id is because I have dozens of these elements on the page. The javascript I'm currently using is:
var targetA = document.getElementbyID(sjDDulC8wt).getElementsbyTitle("Have_it");
targetA.removeClass("have_it").addClass("have_it selected");
When I click the link, the haveItem() function runs, but it doesn't change the class. How can I change my script so that clicking the link will change the class?
I am assuming you are using jQuery since you are using removeClass() and addClass. Otherwise, I would recommend you link to jQuery so that the code below works, or stick with only JavaScript.
var targetA = $('#sjDDulC8wt .have_it');
targetA.addClass('selected');
For future reference, here are some things about your code that you can improve:
getElementById() accepts the id of the element you want to retrieve as a string. Basically, you should wrap your ID in ' or "
Be careful where you are putting spaces and underscores. They are not the same thing. Your list item has the title Have It, while your JavaScript has Have_it.
Capitalization matters. Have_It is not the same thing as Have_it. Be careful with this when you try to get elements by ID.
A class with spaces in it is actually multiple classes. have_it selected actually has both the have_it class and the selected class. Therefore it not necessary to remove have_it and then add have_it selected - you can go straight to adding the selected class.
The function getElementbyTitle() does not currently exist in JavaScript. Also, be careful again about capitalization. Typically, the first letter of every word in a function is capitalized. Thus, if it did exist it would be called getElementByTitle() (notice the B instead of b).
Here:
var anchor = document.querySelector( '#sjDDulC8wt [title="Have It"]' );
if ( anchor ) anchor.classList.add( 'selected' );
Live demo: http://jsfiddle.net/UZfnh/
(Won't work in older browsers.)
This should do the task for you:
<a title="Have It" class="have_it" onclick="this.className+=' selected'">%</a>
However, you should learn about the DOM. None of the methods you used (getElementbyID, getElementsbyTitle, removeClass and addClass) exists.
When you successfully find the element, you can do one of these:
element.classList.add("selected");
It uses a fairly new classList feature available for FF 3.6, IE 10, Chrome 8, Opera 11.50, Safari 5.1 and above. It the the most preferred way to do it once you are sure your clients will have one of those browsers (near future).
element.className += " selected";
className doc. This works and is probably the easiest way. Not so nice as the classList thing, but available for all browsers.
If you can't use jQuery then you can change the classname of an element using className:
var element = document.getElementById("elementId");
element.className = "have_it selected";
Note also this function: getElementsByClassName (HTML5).
As has been pointed out, you have some other issues selecting your element. From your example, it looks like you want to use:
var element = document.getElementById("sjDDulC8wt");
var children = element.getElementsByClassName("have_it");
children[0].className = "have_it selected";
Note that there's no error handling/null checks here. And this handles a simple case of only changing the first child with the specified class, assuming that it exists.
But prefer jQuery if you can use that. From your use of addClass/removeClass it appears that you already expect jQuery.