if this input has value doesn't work in IE 9 - javascript

I am using this simple code to filter through a search form with many text inputs and see if they have a value and then add a class.
Works perfectly in Chrome, safari and Firefox but not in IE9.
$('input[type="text"]').filter(function() {
if ($(this).val() !== '') {
$(this).addClass('used');
}
});
Please advice, thanks in advance!
EDIT
Change to each but doesn't solve the issue... Here it is with the event that triggers the function...
$(document).on('event-ajax-form-is-loaded', function() {
$('input[type="text"]').each(function() {
if ($(this).val() !== '') {
$(this).addClass('used');
}
});
});

From the limited information you shared, this is how you should be doing this:
$('input[type="text"]').filter(function() {
return $(this).val() !== '';
}).addClass('used');
.filter() is supposed to reduce a set of matched elements so its filter function should always return a bool instead of manipulating the DOM.
Edit: Based on your updated code snippet and the page link you shared in the comments, if you are using jQuery in WordPress, then its always safer to wrap the code like so:
(function($) {
/* jQuery Code using $ object */
})(jQuery);

enter code hereIn JS you can check the element value by getting their tag name
for (var i = 0; i < document.getElementsByTagName('input').length; i++){
if (document.getElementsByTagName('input')[i].value == "")
{
alert("The value of textbox at " + i + " is empty");
}
}
Working Demo
Or like what other people suggest, use a .each in JQuery
$('input[type="text"]').each(function(i){
if ($(this).val() == "") {
alert("The value of textbox at " + i + " is empty");
}
});
anohter Working Demo
If you insist to use filter and here you go
$('input[type="text"]').filter(function()
{ return $( this ).val() != ""; }).addClass("used");
Last Working Demo
and jquery filter reference

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.

Place holder is not working

Place holder is not working in IE-9,so I used the below code for place holder.
jQuery(function () {
debugger;
jQuery.support.placeholder = false;
test = document.createElement('input');
if ('placeholder' in test) jQuery.support.placeholder = true;
});
// This adds placeholder support to browsers that wouldn't otherwise support it.
$(function () {
if (!$.support.placeholder) {
var active = document.activeElement;
$(':text').focus(function () {
if ($(this).attr('placeholder') != '' && $(this).val() == $(this).attr('placeholder')) {
$(this).val('').removeClass('hasPlaceholder');
}
}).blur(function () {
if ($(this).attr('placeholder') != '' && ($(this).val() == '' || $(this).val() == $(this).attr('placeholder'))) {
$(this).val($(this).attr('placeholder')).addClass('hasPlaceholder');
}
});
$(':text').blur();
$(active).focus();
$('form:eq(0)').submit(function () {
$(':text.hasPlaceholder').val('');
});
}
});
When I am taking the value of test,it shows null.How can I get the details of all input tag?
I think this will help you
if ($.browser.msie) {
$("input").each(function () {
if (IsNull($(this).val()) && $(this).attr("placeholder") != "") {
$(this).val($(this).attr("placeholder")).addClass('hasPlaceHolder');
$(this).keypress(function () {
if ($(this).hasClass('hasPlaceHolder')) $(this).val("").removeClass('hasPlaceHolder');
});
$(this).blur(function () {
if ($(this).val() == "") $(this).val($(this).attr("placeholder")).addClass('hasPlaceHolder');
});
}
});
}
I'm on my mobile so this is hard but really you need to do
JQuery.support.placeholder = typeof 'placeholder' in test !== 'undefined'
Because null means there isn't any placeholder value, but there is placeholder support
From what I understand you're saying that the placeholder in test is returning null
I suggest you don't write this yourself and go for an off-the-shelf solution. There's more complexity here that you'd probably want to tackle yourself if all you want is provide support for older browsers.
For example, here's the shim I'm using (and that is recommended on http://html5please.com): https://github.com/mathiasbynens/jquery-placeholder/blob/master/jquery.placeholder.js
Go ahead and read the code. These are some issues you need to have in mind when writing such shim:
detect the browser support,
keep track when the box contains the real input or not;
add a class to allow different text colour for the placeholder,
clear the placeholders before submitting the form,
clear the placeholders when reloading the page,
handle textarea,
handle input[type=password]
And that's probably not even all. (The library I've linked also hooks into jQuery in order to make .val() return '' when there's no real input in the box.
There's also another shim that uses a totally different approach: https://github.com/parndt/jquery-html5-placeholder-shim/blob/master/jquery.html5-placeholder-shim.js
This library doesn't touch the actual value of the input, but instead displays an element directly over it.
HTML:
<input type='text' id='your_field' value='Enter value'/>
jQuery:
$(document).ready(function(){
$("#your_field").on('focusout',function(){
if($("#your_field").val() == ''){
$("#your_field").val('Enter value');
}
});
$("#your_field").on('focus',function(){
if($("#your_field").val() == 'Enter value'){
$("#your_field").val('');
}
});
});
See DEMO
Also check when the form is posted because if the user submits the form without entering the field then Enter value will be posted as the value of the field.So do either validations in client side or check in the server side when submitting the form.

Using jQuery to display input TITLE as VALUE (jsfiddle included)

I am trying to come up with a simple jquery input watermark function. Basically, if the input field has no value, display it's title.
I have come up with the jquery necessary to assign the input's value as it's title, but it does not display on the page as if it was a value that was hand-coded into the form.
How can I get this to display the value when the page loads in the input field for the user to see?
Here's the fiddle: http://jsfiddle.net/mQ3sX/2/
$(document).ready(function() {
$(".wmk").each(function(){
var value = $(this).val();
var title = $(this).attr("title");
if (value == '') {
value = title;
}
$(".result").text(value);
// You can see I can get something else to display the value, but it does
// not display in the actual input field.
});
});
Instead of writing your own, have you considered using a ready-bake version? It's not exactly what you asked for, but these have additional functionality you might like (for instance, behaving like a normal placeholder that auto-hides the placeholder when you start typing).
http://www.hagenburger.net/BLOG/HTML5-Input-Placeholder-Fix-With-jQuery.html
http://archive.plugins.jquery.com/project/input-placeholder
Use the below line of code. You need to specify the input element, and update its value. Since your input field has a class called '.wmk', I am using the below code. You can use "id" and use "#" instead of ".". Read more about selectors at http://api.jquery.com/category/selectors/
$(".wmk").val(value);
Updated jsfiddle http://jsfiddle.net/bhatlx/mQ3sX/9/
Update: since you are using 'each' on '.wmk', you can use
$(this).val(value)
I think what you want is this:
$(document).ready(function() {
$(".wmk").each(function(){
var value = $(this).val();
var title = $(this).attr("title");
if (value == '') {
$(this).val(title);
}
$(".result").text(value);
});
});
May be you want something like below,
DEMO
$(document).ready(function() {
$(".wmk").each (function () {
if (this.value == '') this.value = this.title;
});
$(".wmk").focus(
function () {
if (this.value == this.title) this.value = '';
}
).blur(
function () {
if (this.value == '') this.value = this.title;
}
);
}); // end doc ready

Counting the number of input's and textarea's with data

I have a script that only works in jquery 1.7.2. I'm also getting a lot of conflicts with this script.
Is there an alternative to this approach? I'm trying to count the number of input's and textarea's that have data typed inside them. I just need a number.
Here is my current script:
$('#form_register').on('keyup', function() {
var number = $('#form_register').find('input, textarea')
// filter out every empty input/textarea
.filter(function() {
return $(this).val() != '';
}).length;
$('.inputCount').val('There are ' + number + ' empty input fields');
console.log('test');
});​
I'd use the change handler too, to prevent someone paste the text inside a field.
EDIT :
To count upwards as you asked in your comment:
jsBin demo
$('#form_register').on('keyup change', function() {
var number = 0;
$(this).find('input, textarea').each(function(){
if( this.value !== ''){
$('.input_count').val(number++);
}
});
});
To redo to count downwards (DEMO) just use === and exclude the print from the each function:
if( this.value === ''){
number++;
}
$('.input_count').val(number);
If you have more issues, try to wrap the code into:
(function($){ // remap '$' to jQuery
// CODE HERE
})(jQuery);

How do I convert some ugly inline JavaScript into a function?

I've got a form with various inputs that by default have no value. When a user changes one or more of the inputs all values including the blank ones are used in the URL GET string when submitted.
So to clean it up I've got some JavaScript that removes the inputs before submission. It works well enough but I was wondering how to put this in a js function or tidy it up. Seems a bit messy to have it all clumped in to an onclick. Plus I'm going to be adding more so there will be quite a few.
Here's the relevant code. There are 3 separate lines for 3 separate inputs. The first part of the line has a value that refers to the inputs ID ("mf","cf","bf","pf") and the second part of the line refers to the parent div ("dmf","dcf", etc).
The first part is an example of the input structure:
echo "<div id='dmf'><select id='mf' name='mFilter'>";
This part is the submit and js:
echo "<input type='submit' value='Apply' onclick='javascript: if (document.getElementById(\"mf\").value==\"\") { document.getElementById(\"dmf\").innerHTML=\"\"; }
if (document.getElementById(\"cf\").value==\"\") { document.getElementById(\"dcf\").innerHTML=\"\"; }
if (document.getElementById(\"bf\").value==\"\") { document.getElementById(\"dbf\").innerHTML=\"\"; }
if (document.getElementById(\"pf\").value==\"\") { document.getElementById(\"dpf\").innerHTML=\"\"; }
' />";
I have pretty much zero JavaScript knowledge so help turning this in to a neater function or similar would be much appreciated.
your script block in your HEAD:
<script type="text/javascript">
function yourFunctionName(){
...your javascript goes here...
}
</script>
and then your onclick:
onclick="javascript:yourFunctionName()"
Seems pretty simple:
<script>
function doSubmit() {
if (document.getElementById("mf").value == "")
document.getElementById("dmf").innerHTML = "";
if (document.getElementById("cf").value == "")
document.getElementById("dcf").innerHTML = "";
if (document.getElementById("bf").value == "")
document.getElementById("dbf").innerHTML = "";
if (document.getElementById("pf").value == "")
document.getElementById("dpf").innerHTML = "";
}
</script>
<input type="submit" value="Apply" onclick="doSubmit();" />
Or you could even get fancy and do something like this:
<script>
function doSubmit() {
var inputs = {
"mf": "dmf",
"cf": "dcf",
"bf": "dbf",
"pf": "dpf"
};
for (var input in inputs) {
if (document.getElementById(input).value == "")
document.getElementById(inputs[input]).innerHTML = "";
}
}
</script>
if you were to use jquery (and there is no reason not to):
if your submit button had an id of say id="submit-button" this 'should' work and would handle any additional inputs that get added
$(document).ready(function () {
$("#submit-button").click(function () {
$(this).parents("form").find(':input').each(function() {
if ($(this).val() === "") {
$(this).innerHTML = "";
}
});
});
});
NOTE: I did not test above code at all
here is an updated version
$(document).ready(function () {
$("form").submit(function () {
$(this).find(':input').each(function() {
if ($(this).val() === "" && $(this).attr("type") !== "submit") {
$(this).attr('disabled', 'disabled');
}
});
});
});
this one is setting the blank inputs to disabled - I could not get the innerHTML = "" to work on Firefox 3.6 on Mac and I did not test above code on other browsers or OS
you would need to download jquery http://docs.jquery.com/Downloading_jQuery#Current_Release and include a reference to it in your html head
to use the innerHTML trick on the inputs parent span tag change the line $(this).attr('disabled', 'disabled'); to
if ($(this).parent().get(0).tagName === "SPAN") {
$(this).parent().get(0).innerHTML = "";
}

Categories