jQuery input value not working - javascript

Have looked for a solution to this but not found one.
$(document).ready(function() {
if ($("input").value()) {
$("h1").hide();
}
}
So this does not seem to be working ( $("h1").hide() is just a placeholder action... that part is not important, the problem is that the if statement is not working).
There is one form on the page, <input type=text>. I want to make it so that at all times, if there is any text in the input box a certain state is applied. If the input box returns to empty then the state is removed.
There are quite a few other functions inside the $(document).ready function which I omitted due to clarity... but as far as the scope of where the if statement lies it is directly inside of the document.ready function. P.S. The form is shown and hidden dynamically, but it is hard coded -- it is not being created dynamically.
What is wrong with where I have this if statement located?

Try with .val() like
$(document).ready(function(){
if ($("input").val()) {
$("h1").hide();
}
});
Better you use either name or id or class names as selectors.Because input can be of any number and they also includes checkboxes,radio buttons and button types

In jQuery you have to use .val() method and not .value(). Your check should be as follows:
if ($("input").val()) {
$("h1").hide();
}

Unlike .value() in JS, ther's .val() in JQuery.
$(document).ready(function() {
if ($("input").value()) {
$("h1").hide();
}
});
You should use keyup to know when a key is added/removed from the textbox
$(document).ready(function() {
$("#input_data").keyup(function() {
var dInput = $(this).val();
alert(dInput);
});
});
DEMO
NOTE: Since input can be of any number and checkboxes, radio buttons and button types all are included within the HTML input tag, You should use either name or id or class names as **selectors**.
input[type=text]
or, to restrict to text inputs inside forms
form input[type=text]
or, to restrict further to a certain form, assuming it has id myForm
#myForm input[type=text]
If You want a multiple attribute selector
$("input[type='checkbox'][name='ProductCode']")
//assuming input type as checkbox and name of that input being ProductCode

.value() is invalid. You should use .val() instead of .value(). Hope it will make it work?

You should use val at the place of value and the solution is :
$(document).ready(function() {
if ($("input").val()) {
$("h1").hide();
}
});

Related

2 similar forms on the one page, $(this).find(); is getting value from the last form

I have 2 forms on 1 page. I am trying to get the value of the name field from the first form using jQuery but jQuery is always getting the name value from the 2nd form. The code looks like this:
$('#registration-form').each(function(){
var $this = $(this);
$this.submit(function (event) {
var firstName = $(this).find('input[name="firstName"]').val();
console.log(firstName);
});
});
Why is this code not working? Your help is much appreciated!
Firstly you're selecting by id attribute, so you cannot have more than one element with the same id. This is why only one is found. The each() is also redundant in this case.
If you want to group elements use a class instead, although note that the each() is still redundant as jQuery will loop over each selected element internally so you can just attach the submit event handler directly, like this:
$('.reg-form').submit(function (e) {
var firstName = $(this).find('input[name="firstName"]').val();
console.log(firstName);
});

Radio button REQUIRED if input field has content

I have a a reasonably quick problem to solve (I think). I have a form online and it validates the required content for the user's data, but has no validation on the first part of the form.
I've been asked however if I can make a radio button REQUIRED depending on whether an input field has been filled in.
The form can be found here:
http://www.elcorteingles.pt/reservas/livros_escolares/form.asp
So if the person start's filling in the input fields on the first line, that the radio buttons in the group become REQUIRED (for either the CDROM ou CADERNO but not both)
You can handle the focusout and blur events for the input:
$(function () {
// Handle every input type text.
// To select specific inputs, give them a common class and change the
// selector accordingly.
$("input[type=text]").on("focusout blur", function () {
// Check for inputs with class radio_btns which are in
// the parent element (li).
// Set their required property.
$(this).parent().find("input.radio_btns")
.prop("required", $(this).val().trim().length > 0);
});
});
Demo
jQuery reference (Tree Traversal)
jQuery reference (.prop())
jQuery reference (.focusout())
jQuery reference (.blur())
This will work. You can include the following JQuery code in the script tag, and also the JQuery cdn link in the head tag.
$(document).ready(function(){
$('#01titulo').focusout(function(){
if ($(this).val() !== "") {
$('[name="01caderno"]').prop('required', true);
} else {
$('[name="01caderno"]').prop('required', false);
}
alert($('[name="01caderno"]').attr('required'));
});
});
Try using the following js code its working:
$(document).ready(function(){
$(".titulo_books").each(function(){
$(this).focus(function(){
var radioChecked=0;
var currElemId = parseInt($(this).attr('id'));
var radioSelecterId = (currElemId>9) ? currElemId : "0"+currElemId;
$("input:radio[name="+radioSelecterId+"caderno]").each(function(){
if(radioChecked==0)
{
radioChecked==1;
$(this).attr("checked","checked");
}
});
});
});
});
I have checked it by executing this from console on your site and it seems to work fine. You can alter this in the way you want. I have checked one of the four available radio button. User can change the input value if required. Or you can also change the default radio button selected through my code.

Check a checkbox onclick without name or ID

I am trying to come up with some code that I can execute onclick that will check a specific checkbox on a page. The checkbox does not have a unique name and does not have an ID. The only usable identifier is the value.
I am limited to jQuery 1.4.2.
Nothing I have tried will work. Any ideas?
Thanks.
This is obviously something you want to avoid doing but if the value is all you got, you'll have to traverse through the DOM for that input field where type=checkbox and where value is the value that you are looking for. What you can do is write a jQuery select for $('input[type=checkbox]') and there loop through all the checkboxes that have the value that you are looking for.
$checkbox = $('input[type=checkbox]')
$checkbox.each( function(k,v){
if( $(v).attr('val') == somevalue ){ //using attr() instead of .val() since it's a checkbox
$(v).attr('checked',true)
}
}
So I checked out if you can just directly select it in jquery 1.4 using plunkr.
$("input:checkbox[value='someVal']").attr("checked", "checked")
And this works fine. Here's the plunk url to check out http://plnkr.co/edit/2sSjONghE5IfGlAvN2kk?p=preview
This should work in earlier versions of jQuery:
$("input:checkbox[value='someVal']").attr("checked", "checked")
Here is a fiddle.
You can try:
$("input[type=checkbox][value=myvalue]").click(function() {
alert('clicked');
});
You can refer it it by it's index id or by value

option:selected not triggering .change()

I have a dropdown box that has a list of institutions in it. Now if I manually select an option, it works and I am able to grab the correct value.
However, I have a select rates button which uses JavaScript to pull up a rate sheet. You select a rate from that sheet and it will select an option from the dropdown for you (one that corresponds with the rate from the rate sheet). If I use this method, it doesn't trigger a .change() therefor I can't get a value for the selected option.
$('#id_financial_institution').change(function () {
var value = $("#id_financial_institution option:selected").text()
$("fi").text(value);
});
Any suggestions? I have tried .change() and .click() but nothing.
Once you are in the change function you don't have to do another search or selector because you already have the object you just have to find the selected option from it. So you can try this:
$('#id_financial_institution').change(function () {
var value = $(this).find("option:selected").text();
$("fi").text(value);
});
If the code still doesn't return you answer start to add alerts at each point to see where you are and what values you have and work your way from there?
Rather than .text() use .val()
$(function() {
$('#id_financial_institution').change(function () {
var value = $("#id_financial_institution option:selected").val()
alert(value);
});
})
Here is a sample demo, without your html. I am just alerting the value.
DEMO
You're going about this all wrong. You already have the select element in this, all you need is the value of that select element.
$('#id_financial_institution').change(function () {
var value = $(this).val();
$('#fi').text(value); //i assume `fi` is an [id]
//do more stuff
});
I went inside my AJAX call and got the value of the fields I needed there. For some reason, when using the AJAX call, it wouldn't fire the .change() on that particular field.
Thanks for all your input everyone.

How do I clear all the fields in a variable html content? (preferably with jQuery)

I need to reset all the form fields in an HTML content I saved in a variable. I searched the internet and here too. But none of what I've found has worked yet. It won't success even with the simplest method for just text fields:
var content = $(this).prev('.listset').find('ol.multiple > li:last').html();
$(content).find('input[type=text]').val('');
I do not have a form id available.
Use plain old javascript:
document.forms['my_form_name'].reset()
I found this:
This should do the trick if the ID of your form is myform:
$(':input','#myform')
.not(':button, :submit, :reset, :hidden')
.val('')
.removeAttr('checked')
.removeAttr('selected');
It is using the :input selector which will match all input, textarea, select and button elements. Since we are passing #myform as the second argument, it will only find inputs inside this form element. Then it filters out all buttons, submits, resets and hidden inputs using not(). Then it is using val() to set the value of the remaining fields to an empty string, and then it uses removeAttr to remove the checked and selected attribute of the fields in case you have any radio/checkbox/select inputs. Tada.
here: Resetting a multi-stage form with jQuery
EDIT: from same url:
if you have default value's on your checkboxes as well use this one:
// Use a whitelist of fields to minimize unintended side effects.
$(':text, :password, :file, SELECT', '#myFormId').val('');
// De-select any checkboxes, radios and drop-down menus
$(':input', '#myFormId').removeAttr('checked').removeAttr('selected');
is this what you were looking for?
If you're using all textboxes:
for(c in document.getElementById('id_of_form').childNodes) {
c.innerHTML = "";
}
If you're using multiple things, replace childNodes with getElementByTagName("name of tag") and filter with type.
This is a bit of a guess as I don't know what your mark-up looks like but jQuery 'find' may not work depending on how the html string is structured - have a look at this question -
Using jQuery to search a string of HTML
You could try looping through the 'content' string, then update each form element individually and add them to relevant container, something like -
$(content).each(function () {
if (this.nodeName == 'INPUT') $(this).val('');
if (this.nodeName == 'SELECT') $(this).children('option').prop('selected','');
$("#moveto").append(this);
});
Working demo - http://jsfiddle.net/vFMWD/5/

Categories