select with special characters not working - javascript

I have a select box which is
<select>
<option value="">--Select--</option>
<option id="402883273d3fe2bd013d49db55ca0007" value="~`!##$%^&*()_+-={}|[]\:" title="~`!##$%^&*()_+-={}|[]\:">~`!##$%^&*()_+-={}|[]\:</option>
<option id="402883273b660e71013b6ff04187000d" value="asdasd" title="asdasd">asdasd</option>
<option id="402883273952e67f01395332fd5f0006" value="CC-1" title="CC-1">CC-1</option>
<option id="402883273bdb9824013c14d3c2c30007" value="rto" title="rto">rto</option>
<option id="402883273bdb9824013c14d5decf0008" value="xc" title="xc">xc</option>
</select>
and now when i am loading the page and to select option with value = "~`!##$%^&*()_+-={}|[]\:"
its not getting selected.
code for selection is :
var selectedCategory = "<%=StringEscapeUtils.escapeJavaScript(toEditClause.getClauseGroup().getClauseCategory().getName())%>";
console.log("before : "+selectedCategory);
selectedCategory = selectedCategory.replace(/'/g,"\\'");
console.log("After : "+selectedCategory);
jQuery("#clauseCategory_ option[value='"+selectedCategory+"']").attr("selected", "selected");
i think problem is due to special characters because otherwise if i choose some other value like : "CC-1" .. its working fine

Instead of value go for the ID.. ie select on the bases of ID .. so use this jQuery("#clauseCategory_ option[id='"+selectedCategory+"']").attr("selected", "selected");

You can use this solution:
// Escapes special characters and returns a valid jQuery selector
function jqSelector(str)
{
return str.replace(/([;&,\.\+\*\~':"\!\^#$%#\[\]\(\)=>\|])/g, '\\$1');
}

Related

Javascript get value from select option based on label

Using either jQuery or pure JavaScript, how can I get the ID for a select option based on the label? So for example, given the following:
<select id="blah">
<option value="1">One</option>
<option value="2">Two</option>
<option value="3">Three</option>
</select>
If I have the label "Two" but I need to know the value associated with it, how can I get that value from this select? I don't want to simply select it, I need to know what the value is.
If the only reference you have is really the actual text content, then you'll have to loop through the elements and check the content of each one. Shown here with jQuery just because it's less to type:
var result;
$("option").each(function() {
if ($(this).text() == "Two") {
result = $(this).attr("value");
return false;
});
});
Another option:
$('#blah').find('option:contains("Two")').val();
(Pun intended?)
Get all the options and then use find to get the one with specific text.
const optionEls = Array.from(document.querySelectorAll("#blah option"));
const hasText = text => el => el.textContent === text;
const optionWithTwo = optionEls.find(hasText("Two"));
console.log(optionWithTwo.value);
<select id=blah>
<option value=1>One</option>
<option value=2>Two</option>
<option value=3>Three</option>
</select>

jQuery - Set the selected option of a select box using value or text with options nested in optgroups

So I am writing an app that requires an address input and I have a select element for the user to select the state/province. It needs to support the US and Canada so it has nested optgroups to separate those out and a single, first level option as it's default value. Here is a basic example:
<select name="state" id="state">
<option class="co" value="" data-placeholder="true" disabled selected>Choose your state...</option>
<optgroup label="United States">
<option class="co" value="AL">Alabama</option>
<option class="co" value="AK">Alaska</option>
<option class="co" value="AZ">Arizona</option>
</optgroup>
<optgroup label="Canada">
<option class="co" value="AB">Alberta</option>
<option class="co" value="BC">British Columbia</option>
<option class="co" value="MB">Manitoba</option>
</optgroup>
Now I need to programmatically select the option that matches input from an external source and I want to check for a match based on both the value of the option element or its text. Whichever option is a match would then be set as the selected option. I know you can set the selected option by value using
$("#state").val(myValue)
and I know you can set an option based on text in this way
var myText = "The state I want.";
$("#state").children().filter(function() {
return $(this).text() == myText;
}).prop('selected', true);
Is there a clean way to do this without having to run through each child and checking if it's an optgroup and then running through all its children to check for a match? Is there an easy way through jQuery to combine the value and text methods of setting the selected option?
One other complication, I am going to be doing this within an external jQuery plugin. Within the function I need to modify I have the select element as a variable
$element
so I need a way to do it kind of like this if possible:
$element.descendents(":option").filter(function() {
//do the selecting here
}).prop('selected', true);
If you want to select by the option value, use the value selector:
var myText = "AZ";
$('#state option[value="' + myText + '"]').prop('selected', true);
If you want to search by the option's label, use a filter:
var myText = "Arizona";
$('#state option').filter(function () { return $(this).html() == myText; }).prop('selected', true)
Solved. Since I already had my element passed to a function as a jQuery variable, $element, I couldn't just use the standard selector in the form of:
$("#state option").filter(
// filter function
).prop('selected', true);
After a lot of trying, I got this and it works:
function functionIHadToChange($element, value) {
// other code
$element.find("option").filter(function(){
return ( ($(this).val() == value) || ($(this).text() == value) )
}).prop('selected', true);
}
I am not sure I understood completely your question but I am attempting to answer it in this fiddle
The trick being that you can select it by setting the value of the select box directly
$("#state").val( a_value );
You can set it by $("#select_id").prop("selectedIndex", 3); // Select index starts from zero.
Read here for example this.
$element = $('select#state');
$options = $element.find('option');
$wanted_element = $options.filter(function () {
return $(this).val() == "Alabama" || $(this).text() == "Alabama"
});
$wanted_element.prop('selected', true);
Would be one way to do it.
But i would guess, without knowing the exact internas of the .find() method, in the end jQuery will use at least two loops itself to perform this...
I'm late here but for future visitor, easiest way to do that is :
html
<select name="dept">
<option value="">This doctor belongs to which department?</option>
<option value="1">Orthopaedics</option>
<option value="2">Pathology</option>
<option value="3">ENT</option>
</select>
jQuery
$('select[name="dept"]').val('3');
Output: This will active ENT.

How can i replace value from the option tag value attribute

I have a below scenario. Actually, by the process the after rendering the html dropdown box is display the value like below
<select id="ht" class="input-box quick-jump-menu" name="ht">
<option selected="selected" value="">Jump straight to a below option</option>
<option value="<span id="_SE_CP" _SE_CPt="default">Lakeside</span>">
Lakeside
</option>
<option value="<span id="_SE_CP" _SE_CPt="default"></span>">
Alvaston
</option>
by some process, it is using some span tag there, i need only url in the value attribute like below
<select id="ht" class="input-box quick-jump-menu" name="ht">
<option selected="selected" value="">Jump straight to a below option</option>
<option value="Google.co.uk">
Lakeside
</option>
<option value="http://www.google.com">
Alvaston
</option>
Here, i need only set the URL value in the "Value" attribute of the "option" tag. i think this can be done through jquery.
Please suggest any one if possible and help will be much appreciated
​var tempDiv=$('<div/>');
$('#ht option').each(function(){
tempDiv.html($(this).val());
$(this).val(​​​​​​​​​​​​​​​​​​​​​​​​​​​tempDiv.find('a').attr('href'));
});
The above code uses a temporary div (tempDiv) to capture the html from the option value and extract the href value.
Demo (select an option): http://jsfiddle.net/A7nyd/
[Update] this is actually the same answer as #chrisgonzalez.
If you're rendering the option tag like this and you want to change it on the client side, here's a quick but dirty solution:
$("#ht option").each(function(){
$(this).attr("value", $($(this).attr("value")).find("a").attr("href"));
});
First off there is an error with the current HTML.. All the html inside of the value have double quotes.
Encase that inside single Quotes or escape the ones inside.
Try this
​$('#ht')​.after('<div id="check"></div>');
​$('#ht option').each(function(){
if(this.value != ''){
var $check = $('#check');
var str = this.value;
$check.append(str);
var href = $check.find('a').attr('href');
this.value = href;
$check.empty();
}
});
$('#check').remove();
Check Fiddle
with jQuery:
$('option').attr({value: 'new src'});
Try this:
$("#ht option").each(function()
{
$(this).val($(this).val().find("a").attr("href"));
});

HTML/JS: Validating value in <selected>-list

I'm really new to this and working on a JavaScript code and I want to see if a dropdownlist has any choosen value. How do i do that?
I tried:
var selectObj = form.document.getElementById('myListId');
var selectInd = selectObj.selectedInd;
and tried:
if(selectInd == "")
to check if it was empty.
What do I need to change to make it work?
Thanks in advance!
A drop-down, by design, always has a value selected. If you just want to leave an empty value first to not choose something for the user, you can simply check if it's value is empty.
document.getElementById("validate").onclick = function() {
if (document.getElementById("foo").value == "")
alert("invalid");
else
alert("valid");
};
Live example
According to comments, this might not work in older versions of IE. Be sure to test it there if you need to support those browsers.
HTML
<select id="myListId">
<option value="">- Select an option-</option>
<option value="1">Option 1</option>
<option value="2">Option 2</option>
<option value="3">Option 3</option>
</select>
Javascript
function checkvalue(){
var selectObj = form.document.getElementById('myListId');
if (selectObj.value != "") {/* DO something */}
}
Now you can execute this function on change of the select box, or when you submit the form, it is up to you.
Try to read this example.
You are trying compare a number (selectObj.selectedIndex) with a string (""), you should write something like this:
var selectObj = document.getElementById('myListId'),
selectInd = selectObj.selectedIndex,
selectedVal = selectObj.options[selectInd].value;
if(selectedVal== "") {
/* do your stuff*/
}
Only to notice: This only would work (detect a value equal to "") with an html like this:
<select id="myListId">
<option value="" selected="selected">Empty value</option>
<option value="1">Non empty value</option>
</select>
Or when the user has been selected the option "Empty value".
EDIT:
Try with this demo. This demo also works in IE7.

javascript function not getting dropdown text

i am using javascript to get the text of selected item from dropdown list.
but i am not getting the text.
i am traversing the dropdown list by name..
my html dropdownlist is as:
<select name="SomeName" onchange="div1();">
<option value="someVal">A</option>
<option value="someOtherVal">B</option>
<option value="someThirdVal">C</option>
</select>
and my javascript is as:
function div1() {
var select = document.getElementsByName("SomeName");
var result = select.options[select.selectedIndex].text;
alert(result);
}
can you please help me out..
Option 1 - If you're just looking for the value of the selected item, pass it.
<select name="SomeName" onchange="div1(this.value);">
<option value="someVal">A</option>
<option value="someOtherVal">B</option>
<option value="someThirdVal">C</option>
</select>
function div1(val)
{
alert(val);
}
Option 2 - You could also use the ID as suggested.
<select id="someID" name="SomeName" onchange="div1();">
<option value="someVal">A</option>
<option value="someOtherVal">B</option>
<option value="someThirdVal">C</option>
</select>
function div1()
{
var ddl = document.getElementById("someID");
var selectedText = ddl.options[ddl.selectedIndex].value;
alert(selectedText);
}
Option 3 - You could also pass the object itself...
<select name="SomeName" onchange="div1(this);">
<option value="someVal">A</option>
<option value="someOtherVal">B</option>
<option value="someThirdVal">C</option>
</select>
function div1(obj)
{
alert(obj.options[obj.selectedIndex].value);
}
getElementsByName returns an array of items, so you'd need:
var select = document.getElementsByName("SomeName");
var text = select[0].options[select[0].selectedIndex].text;
alert(text);
Or something along those lines.
Edit: instead of the "[0]" bit of code, you probably want either (a) to loop all items in the "select" if you expect many selects with that name, or (b) give the select an id and use document.getElementById() which returns just 1 item.
The problem with the original snippet posted is that document.getElementsByName() returns an array and not a single element.
To fix the original snippet, instead of:
document.getElementsByName("SomeName"); // returns an array
try:
document.getElementsByName("SomeName")[0]; // returns first element in array
EDIT: While that will get you up and running, please note the other great alternative answers here that avoid getElementsByName().

Categories

Resources