Where is my mistake using JavaScript and jQuery - javascript

I have a question actually I need one if/else for hide or show one div, I had wrote the following function but it didn’t work:
jQuery(document).ready(function(){ /*show div OtraUniversidad when option:selected = 165*/
var optionValue = $("#Universidad option:selected").val();
$("#OtraUniversidad").hide();
if(optionValue == 165){
$("#OtraUniversidad").show();
}
});
Actually works: $("#OtraUniversidad").hide();
I don't know what's wrong; I'm new in JavaScript and jQuery
Some help is always welcome.

I think this should work:
jQuery(document).ready(function() {
$('#Universidad').change(function() {
var optionValue = $("#Universidad").val();
if(optionValue == 165) {
$("#OtraUniversidad").show();
} else {
$("#OtraUniversidad").hide();
}
}).change();
});
Demo: http://jsfiddle.net/gGX2E/1/

optionValue == 165
This comparison is wrong, you must use this:
if(optionValue == "165")

Related

How to select an item by text/label? [duplicate]

I need to check if a <select> has an option whose text is equal to a specific value.
For example, if there's an <option value="123">abc</option>, I would be looking for "abc".
Is there a selector to do this?
Im looking for something similar to $('#select option[value="123"]'); but for the text.
This could help:
$('#test').find('option[text="B"]').val();
Demo fiddle
This would give you the option with text B and not the ones which has text that contains B.
For recent versions of jQuery the above does not work. As commented by Quandary below, this is what works for jQuery 1.9.1:
$('#test option').filter(function () { return $(this).html() == "B"; }).val();
Updated fiddle
You can use the :contains() selector to select elements that contain specific text.
For example:
$('#mySelect option:contains(abc)')
To check whether a given <select> element has such an option, use the .has() method:
if (mySelect.has('option:contains(abc)').length)
To find all <select>s that contain such an option, use the :has() selector:
$('select:has(option:contains(abc))')
None of the previous suggestions worked for me in jQuery 1.7.2 because I'm trying to set the selected index of the list based on the value from a textbox, and some text values are contained in multiple options. I ended up using the following:
$('#mySelect option:contains(' + value + ')').each(function(){
if ($(this).text() == value) {
$(this).attr('selected', 'selected');
return false;
}
return true;
});
I faced the same issue below is the working code :
$("#test option").filter(function() {
return $(this).text() =='Ford';
}).prop("selected", true);
Demo : http://jsfiddle.net/YRBrp/83/
This worked for me: $("#test").find("option:contains('abc')");
This is the best method for select text in dropdownlist.
$("#dropdownid option:contains(your selected text)").attr('selected', true);
I tried a few of these things until I got one to work in both Firefox and IE. This is what I came up with.
$("#my-Select").val($("#my-Select" + " option").filter(function() { return this.text == myText }).val());
another way of writing it in a more readable fasion:
var valofText = $("#my-Select" + " option").filter(function() {
return this.text == myText
}).val();
$(ElementID).val(valofText);
Pseudocode:
$("#my-Select").val( getValOfText( myText ) );
This work for me
$('#mySelect option:contains(' + value + ')').attr('selected', 'selected');
Use following
$('#select option:contains(ABC)').val();
For jquery version 1.10.2 below worked for me
var selectedText="YourMatchText";
$('#YourDropdownId option').map(function () {
if ($(this).text() == selectedText) return this;
}).attr('selected', 'selected');
});
This works for me:
var result = $('#SubjectID option')
.filter(function ()
{ return $(this).html() == "English"; }).val();
The result variable will return the index of the matched text value. Now I will just set it using it's index:
$('#SubjectID').val(result);
This will work in jQuery 1.6 (note colon before the opening bracket), but fails on the newer releases (1.10 at the time).
$('#mySelect option:[text=abc]")
That was 10 years ago.
Now jquery is EOL, we can use ordinary DOM for this simple job
document.getElementById("SomeSelectId").querySelectorAll("option").forEach(o => o.selected = o.innerText == text);
August 25, 2022.
For jQuery v3.5.1 what really worked for me is this:
$('#selectID option:contains("label")').prop('selected', true);
If you have the text in a variable, do this:
ddText = 'Text to find';
$('#selectID option:contains("' + ddText + '")').prop('selected', true);
use prop instead of attr
$('#mySelect option:contains(' + value + ')').each(function(){
if ($(this).text() == value) {
$(this).prop('selected', 'selected');
return false;
}
return true;
});
This what worked for me on jquery V3.6.0 in 2022
$("#select >option").filter( function()
{
if ($(this).text() === "123")
{
$(this).prop("selected", true);
}
});
This will also work.
$('#test').find("select option:contains('B')").filter(":selected");
As described in this answer, you can easily create your own selector for hasText. This allows you to find the option with $('#test').find('option:hastText("B")').val();
Here's the hasText method I added:
if( ! $.expr[':']['hasText'] ) {
$.expr[':']['hasText'] = function( node, index, props ) {
var retVal = false;
// Verify single text child node with matching text
if( node.nodeType == 1 && node.childNodes.length == 1 ) {
var childNode = node.childNodes[0];
retVal = childNode.nodeType == 3 && childNode.nodeValue === props[3];
}
return retVal;
};
}
This works for me
var options = $(dropdown).find('option');
var targetOption = $(options).filter(
function () { return $(this).html() == value; });
console.log($(targetOption).val());
Thanks for all the posts.
Either you iterate through the options, or put the same text inside another attribute of the option and select with that.

ComboBox hide and show div

I have a problem in populating or regarding the response of my javascript.
I have two different which is and . The div#individual represents the first form that has a a div#address. And I have my second div which is the div#group. My problem is when i choose the "individual" in the subtype combobox the div#address works perfectly but when it comes to the "group" in the subtype combobox it doesn't respond like the first one. I set the div#address with the same class. Didn't work.
How ca I solved this?
Note: Im just using .hide() and .show() for both div#individual and div#group. Thanks!
the inputs of address for individual and the inputs of address for group should use different id and name.
The below code is useful for u please try it?
<script id="main" type="text/javascript">
$(document).ready(function()
{
var val=$("#selectid option:selected").text();
if(val == "Internet")
{
$("#new1").show();
$("#new2").hide();
}
else if(val == "Media")
{
$("#new1").hide();
$("#new2").show();
}
$('#selectid').change(function()
{
var val=$(this).val();
$("#internet").val('');
$("#media").val('');
if(val == "Internet")
{
$("#new1").show();
$("#new2").hide();
}
if(val == "Media")
{
$("#new1").show();
$("#new2").hide();
}
val = "";
});
});
</script>

JQuery Toggle property contentEditable = "true"

I am using contenteditable="true" in a div
What I want to do it to toggle true and false on this attribute everytime I click on a div.
example:
$( "#mylabel" ).click(function() {
$('#editablediv').attr('contenteditable','false');
});
I tried:
$( "#mylabel" ).toggle(function() {
$('#editablediv').attr('contenteditable','false');
});
but that didn't work
How can I do this?
Try this way:
$( "#mylabel" ).click(function() {
var value = $('#editablediv').attr('contenteditable');
if (value == 'false') {
$('#editablediv').attr('contenteditable','true');
}
else {
$('#editablediv').attr('contenteditable','false');
}
});
Keep me posted, hope this helped
Here is shorter than your shortest (Reusability and Character Count):
function editTheElement() {
var a = "contenteditable";
$(this).attr(a) === 'true' ? $(this).attr(a,'false') : $(this).attr(a, 'true');
}
or still
function editTheElement(e) {
var a = "contenteditable";
e.attr(a) === 'true' ? e.attr(a,'false') : e.attr(a, 'true');
}
or
function editTheElement(e) {
var a = 'contenteditable';
var v= e.attr(a);
e.attr(a,!v);
}
or
function editTheElement(e) {
var a = 'contenteditable';
e.attr(a,!e.attr(a));
}
or
function editTheElement(e) {
e.attr('contenteditable',!e.attr('contenteditable'));
}
JS is fun :)
In 2018 at least, most of these answers aren't working past the first on/off in Chrome 68. It's something with how jQuery or the browser is reading the value of this attribute, because the logic is pretty simple.
The code I found to work was
var el = $("{your selector}")
(el.attr('contenteditable') ?
el.removeAttr('contenteditable') :
el.attr('contenteditable', true));
Demo Fiddle
shortest solution I found:
$('[contenteditable]').attr('contenteditable') === 'true' ?
$('[contenteditable]').attr('contenteditable', 'false') :
$('[contenteditable]').attr('contenteditable', 'true');
$('#mylabel').click(function() {
editable = $('#editablediv').attr('contenteditable');
$('#editablediv').attr('contenteditable', !(editable == 'true'));
});

jQuery: check the value of all <select>s on a page

I have a form with several <select> elements on it.
I'd like to check that the value of all select elements is '0'. How can I do this elegantly?
Currently I have this:
var all_zero = true;
$('myform select').each(function() {
if ($(this).val() !== '0') {
all_zero = false;
}
});
if (all_zero) { //do something
Does anyone know a nicer way to do it?
Test for the value in the selector.
var non_zero = $('myform select[value!="0"]').length;
if (non_zero === 0) { //do something
So if there's no select that does not have the value "0", non_zero === 0 will be true.
That is the correct way to do it, one way for getting it cleaner is only declaring a variable when necessary. like so:
$('myform select').each(function() {
if ($(this).val() !== '0') {
some_zero = true;
}
});
if (!some_zero) { //do something
Your code is nice and you can try :
var all_zero = $('myform select').filter(function(){return $(this).val()!='0'}).length>0

jQuery: FadeIn a selected value on click

I have a selected box with 5 values. I'm trying to fadeIn inputs of what is selected in the box. For example: If input1 is selected, fade in input1 on click.
Here is what I'm trying to do:
$(document).ready(function(){
$('.btn').click(function() {
if($("#selectbox").value == 'Input1') {
$(".input1").show();
} else if($("#selectbox").value == 'Input2') {
$(".input2").show();
} else if($("#selectbox").value == 'Input3') {
$(".input3").show();
} else if($("#selectbox").value == 'Input4') {
$(".input4").show();
} else if($("#selectbox").value == 'Input5') {
$(".input5").show();
}
}
});
And here is a NOT working fiddle:
http://jsfiddle.net/rzMHJ/
Your code have two errors and that's why its not working.
$("#selectbox").value should be $("#selectbox").val()
you have not closed your click event with );
Also its much better to use switch case in this example.
Working Demo: http://jsfiddle.net/naveen/Zn2yy/
Update (based on Nick Cravers comment)
For this particular scenario you could simplify code a lot like this.
Demo: http://jsfiddle.net/nick_craver/BWacA/
There are two problems with your code that is causing it to fail.
First, replace .value with the jQuery function val().
Second, add ); to the second to last } at the end.
Here is working refactored code:
$(document).ready(function() {
$('.btn').click(function() {
var show = "." + $("#selectbox").val().toLowerCase();
$(show).fadeIn();
});
});

Categories