Checking if a selected element contains an attribute - javascript

I have two types of lists appended to my select element.
a list of users: <option value="domain\davidr" userid="108">David</option>
a list of groups: <option value="Test Group" groupid="10">Test Group</option>
This is my select html:
<select id="groupOwner">
<option value="default" disabled>Select a Group Owner</option>
<optgroup label="---Users---"></optgroup>
</select>
I need to set a variable as either "user" or "group" based on the selected list item type.
I tried doing this: var ownerType = $("#groupOwner[groupid]") ? "group" : "user"; but it keeps returning "group"

Firstly, groupid and userid are not valid attributes for the option element and will render your page invalid. Use data-* attributes instead:
<!-- Example user item -->
<option value="domain\davidr" data-userid="108">David</option>
<!-- Example group item -->
<option value="Test Group" data-groupid="10">Test Group</option>
Secondly, #groupOwner is the select, whereas you need to check the data attribute of the selected option. Try this:
var ownerType = $("#groupOwner option:selected").data('groupid') ? "group" : "user";
Example fiddle

$("selector").get(0).hasAttributes("attributes");

Your selector will always be evaluated to true: if there's no match for your selector, jQuery returns an empty array, which will be evaluated to true in your ternary test.
You should test the length of the array returned by jQuery to determine whether your element is on the DOM or not.
Example :
// Will print No, foo isn't an HTML element present on the DOM
$('foo').length ? console.log('Yes') : console.log('No');
// Will print Yes, $('foo') = []
$('foo') ? console.log('Yes') : console.log('No');

Related

Check how many selects have had an options selected using jQuery

I got a bunch of selects:
<select name="paraquien" class="selectpicker form-control paraquien" id="paraquien" onchange="mostrarPreguntas();">
<option value=""><?=__('¿Para quién es el plan?')?><span class="glyphicon glyphicon-triangle-bottom"></span></option>
<option value="1"><?=__('Para mi')?> <span class="glyphicon glyphicon-triangle-bottom"></span></option>
<option value="2"><?=__('Para regalar')?><span class="glyphicon glyphicon-triangle-bottom"></span></option>
</select>
and I would like to know if all of them have been selected, and in that case trigger an event. I've tried this far:
jQuery('.paraquien option:selected')
Getting this result array:
[
<option value=​"1">​Para mi ​</option>​,
<option value=​"1">​Hombre​</option>​,
<option value=​"3">​Estudiante​</option>​,
<option value>​Su situación sentimental​</option>​,
<option value>​¿Tiene hijos?​</option>
​]
You can see every option selected has a value attribute set, what I would like to know is how to get just the options which value has been already set, in the same selector mentioned before.
Any Idea?
You can use filter() to check for select elements where the value is still ''. Try this:
var $unchosenSelects = $('.paraquien').filter(function() {
return $(this).val() == '';
});
if ($unchosenSelects.length) {
// there was at least one select within nothing chosen...
}
Similarly you could use map() to get all the values in an array, then $.inArray to check for empty strings:
var chosenValues = $('.paraquien').map(function() {
return $(this).val();
});
if ($.inArray(chosenValues, '') != -1) {
// there was at least one select within nothing chosen...
}

Empty option as default select when ngoptions data is bound asynchronously

I have the ngoptions array bound asynchronously inside my controller. When I create a select with it, there is an empty option being created. How do I avoid?
<select data-ng-model="order.employee" ng-options="employee._id as employee.name for
employee in employeess"> </select>
My controller code
Employees.query(function(employees){
$scope.employees = employees
});
How do I avoid empty select being created? I tried ng-init but it didn't work
Solution
(1) You can create blank option. This will be selected by default.
$scope.order.employee = -1
<select data-ng-model="order.employee" ng-options="employee._id as employee.name for
employee in employeess">
<option value="-1">--Select--<option>
</select>
(2) You can select first option
Employees.query(function(employees){
$scope.employees = employees
$scope.order.employee = employees.length ? employee[0]._id : -1
});
That's because you didn't initialized your model.
You have to set a default value for your ng-model="order.employee" in your controller.
Like:
$scope.order.employee = -1
and your select should have this structure:
<select data-ng-model="order.employee" ng-options="employee._id as employee.name for
employee in employeess">
<option value="-1">Click to Select<option>
</select>

Display option fields (child) based on parent option condition - JS solutions needed?

I am looking for a simple .js solution. I have two dropdown buttons - code:
<select name="parent_dropdown" id="parent">
<option value="option_01">parent_option_01</option>
<option value="option_02">parent_option_02</option>
</select>
<br />
<select name="child_dropdown" id="child">
<option value="opt01">child_option_01</option>
<option value="opt02">child_option_02</option>
<option value="opt03">child_option_03</option>
<option value="opt04">child_option_04</option>
</select>
Now I need to accomplish this:
When option_01 in #parent is chosen ---> make available only child_option_01 and child_option_02 in #child dropdown
When option_02 in #parent is chosen ---> make available only child_option_03 and child_option_04 in #child dropdown
I tried some solutions I found online but so far no luck. I have a very basic .js knowledge.
Link to FIddle: http://jsfiddle.net/q5kKz/343/
Help will be appreciated.
Taking the next step with your fiddle, this will do (almost) what you want:
$('#parent').change(function() {
$("option[value='opt01']")[$(this).val() == "option_01" ? 'show' : 'hide']("fast");
}).change();
Notice the attribute selector: "option[value='opt01']" - that says "any options with value of opt01".
You should probably expand that selector to be "#child option[value='opt01']"
Using a "basic" programming method, you could do this for multiple options:
$('#parent').change(function() {
$("option[value='opt01']")[$(this).val() == "option_01" ? 'show' : 'hide']("fast");
$("option[value='opt02']")[$(this).val() == "option_01" ? 'show' : 'hide']("fast");
// Adding multiple options here. This is a bad method for maintainability
}).change();
A better way to go would be to assign some sort of other attributes to the options that should show depending on which parent is selected. One example is using a class that matches the parent value desired - which would require modifying your child list like so:
<select name="child_dropdown" id="child">
<option value="opt01" class="option_01">child_option_01</option>
<option value="opt02" class="option_01">child_option_02</option>
<option value="opt03" class="option_02">child_option_03</option>
<!-- The below option would show whenever the parent is on option 2 OR 3 -->
<option value="opt04" class="option_02 option_03">child_option_04</option>
</select>
But then your script could be much more usefully constructed like so, and wouldn't need to be changed if you added / changed options:
$('#parent').change(function() {
var val = $(this).val();
$("#child option")[$(this).hasClass(val) ? 'show' : 'hide']("fast");
}).change();
This still leaves the problem of the list option hiding, and the select can still be set to a "hidden" value. This would need to be addressed somehow. Something like the below:
$('#parent').change(function() {
var val = $(this).val();
$("#child option")[$(this).hasClass(val) ? 'show' : 'hide']("fast");
var child_val = $('#child').val();
// If the selected option is not visible...
if ($('#child').find(":selected").not(":visible")) {
// Set it to the first option that has the proper parent class
$("#child").val($("#child option." + val + ":first").val());
};
}).change();
With newer versions of jQuery you could do something like:
var group1 = $("#child").find("option[value='opt01'], option[value='opt02']");
var group2 = $("#child").find("option[value='opt03'], option[value='opt04']");
$('#parent').change(function() {
var selected = $("#parent").find(":selected").text();
if (selected == "parent_option_01") {
group1.prop("disabled", false);
group2.prop("disabled", true);
} else {
group1.prop("disabled", true);
group2.prop("disabled", false);
}
}).change();
The other people may have it right. But when you want to make changes you have to change a bunch of JS code. I think this is a better approach. In our child HTML we add a data attribute to show what values of parent will make this child option show. This way if we ever need to add more elements or change what ones make the children appear we can just change the HTML and it leaves our javascript a lot cleaner.
http://jsfiddle.net/q5kKz/348/
var parent = $("#parent");
var child = $("#child");
var val;
$('#parent').change(function() {
//Get value of parent
val = $("#parent").val();
//cycle through children and find which data show matches the parent
child.children().each(function(){
var c = $(this);
//Jquery's .data wasn't working for some reason
if(c.attr("data-show") === val){
c.show()
}else{
c.hide()
}
})
}).change();
In the HTML
<select name="parent_dropdown" id="parent">
<option value="option_01">parent_option_01</option>
<option value="option_02">parent_option_02</option>
</select>
<br />
<select name="child_dropdown" id="child">
<option value="opt01" data-show="option_01">child_option_01</option>
<option value="opt02" data-show="option_01">child_option_02</option>
<option value="opt03" data-show="option_02">child_option_03</option>
<option value="opt04" data-show="option_02">child_option_04</option>
</select>

select with special characters not working

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');
}

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