I have a script that looks at a popup modal with a form and should get the first input and focus to that. The forms can change and the input id will always be different.
I am catching the id with var item_id = $('.otf_itm [id]').first().prop('id'); This returns the first. In on case the input has an id of town_name. The problem is that the item does not focus when I use the $('#' + item_id).focus(); How can I get the form item to focus? I have used this method successfully before to get data using .val() and other manipulate parts of the page
// works
$('#town_name').focus();
// doesnt work
$('#' + item_id).focus();
$("#myForm input:first").focus();
Will focus the first input element. Whatever the first input element is.
Remark <select> elements do not fall under this category.
Related
I have a form where the user can dynamically add or remove sets of fields. For each set of fields, when the user enters/changes a value in the upc[] text input I want to make an Ajax query and populate the corresponding desc[] text input. I can capture the change event, but have not been able to read or modify the dynamically create desc[] field:
This snippet does not have the Ajax call as for now I just want to know I can set desc[x].val(). I have tried to associate the dynamic field with a parent element that existed when the DOM was created...but still no luck.
$(document).on('change', '.upcScan', function(){
var upcIdx = $(this).index('.upcScan');
var upcVal = $(this).val();
alert ("The current index is "+upcIdx+" and the value is "+upcVal);
var descName = "desc["+upcIdx+"]";
var descVal = $("#addClient input[name='"+descName+"']").val();
alert("desc field is "+descName+" and value is "+descVal);
});
The code above returns null. If I try to set the val nothing happens.
What am I missing?
I'm using a fake select box in my script which means the original select box is hidden and for styling purposes a ul is showing up. Whenever the selected value of this list changes the orginal select box does too.
There is a change function for that. Within that function is following code:
var el = $(e.currentTarget) ;
$('#my_select_box').children().removeAttr('selected');
$('#my_select_box option[value="'+el.attr('data-value')+'"]').attr('selected','selected');
After that change I want to retrieve the new selected value of the original select box in another function.
But the normal selector only gets the original value, not the new:
$('#my_select_box option:selected').val() //returns the wrong value
So how to I get the new value in the function I need it?
I tried this function:
$("#my_select_box").bind("DOMSubtreeModified", function() {
console.log($(this).find('option:selected').val());
});
It returns the correct value but not where I need it. So how can I retrieve the correct select box value out of the domtree live?
Thanks in advance!
instead of .attr('selected','selected');, try .prop('selected', true);
I have a form in which a user can click a button and add additional fields as needed. Later on, user clicks submit, i do some error checking via ajax. if the additional fields are blank, i want to highlight them in red to let user know its required data.
jquery to add row:
$('#addPerson').click(function(){
var row = "<div id='row_"+rowNum+"'><div class='leftBigRow'><input type='text' class='field' id='addPerson[name][]' name='addPerson[name][]' placeholder='persons name'></div>";
$('.additionalPeople').append(row);
rowNum++;
my ajax call returns a string of field ids that have errors. for example result could be:
//firstname,lastName,zipCode,...etc
so my errorcheck is:
if(result.length > 0)
{
var errors = result.split(",");
for (i=1;i<errors.length;i++)
{
alert(errors[i]);
$('#'+errors[i]).addClass('error');
alert($('#'+errors[i]).val());
}
$("#subForm").attr("disabled", "disabled");
}
the first alert returns what i would expect "addPerson[name][0]";
the second alert returns undefined. telling me it cant find that field....
i have added a fiddle:fiddle
in my fiddle var result is a representation of what i get back from the ajax call. my ultimate goal is to get each field added by pressing yes to turn red if blank....
You don't have an element with id equal to "addPerson[name][0]". When adding new input elements to DOM, you have to include rowNum in their id and name attributes.
Do not include "[" and "]" in name/id attributes. Use:
var row = "<div id='row_"+rowNum+"'><div class='leftBigRow'><input type='text' class='field' id='addPerson_name_"+rowNum+"' name='addPerson_name_"+rowNum+"' placeholder='persons name'></div>";
When you declare your dynamic element's id, you cannot use an array there. You can concatenate it with the rowNum count that you already have.
I have updated your JSFiddle here: http://jsfiddle.net/Myra4/3/
(Observe how I changed the dynamic element's id and your simulated 'result' variable)
I did it in JSFiddle for you so you can immediately verify that it works.
Use .on to bind later created DOM elements.
http://api.jquery.com/on/
Here's the function that checks if the form is complete.
So, what I'm trying to do:
If radio is not selected, throw a message.
If radio is "yes", but text is not entered, throw error.
If radio is "no" but text is entered, make the text empty.
If all is good, add stuff into `allResponses
The form was displayed 5 times, and input was as follows:
Yes a1
No
Yes a3
No
Yes
Now, this input should display an error since in 5th case, "yes" is selected but nothing is entered in the textbox.
However, I get this:
http://i.imgur.com/ya2CUp0.png
Also, the text is not being updated as in 1st and 3rd cases.
I don't know a lot about JS, so please provide me with as explained responses as you can.
EDIT: Complete code: http://pastebin.com/scNSNM2H
Thanks
You have this in a loop:
var exaggerationPart = document.getElementById('exaggeration').value
And then you check to make sure it has a value for each item. But you will get the same value each time.
You are creating multiple inputs with the same id, "exaggeration". This is invalid HTML. Id's must be unique. To correct this, you can increment the id the same as you are doing with other elements (such as, input[name='response"+thisJokeIndex+"']).
var exaggerationPart = document.getElementById('exaggeration' + thisJokeIndex).value
tipTD2.append("<input type='text' name='exaggeration' id='exaggeration" + tipIndex + "' size='70'>")
Working demo: jsfiddle.net/svvge/2
Edit: To clear the value of the text box, you must change the value property of the text box element. Right now you are just changing the value of a variable.
var exaggerationInput = document.getElementById('exaggeration' + thisJokeIndex).value;
var exaggerationPart = exaggerationInput.value;
exaggerationInput.value = '';
I programmed a select box for a client which come to find out gets re-scripted by a third-party JavaScript function into a bunch of divs and spans, then finally a hidden element which contains the selected value from choosing the div/span element. There is another select box which I programmed just underneath this select box which is dependent on the value of the first select box (i.e. the user chooses a country, then if the country contains regions such as USA and Canada, a state select box appears). In any case, I thought it would be best to just add an onChange event to the newly created hidden element from the first select box and then write my own JavaScript function which would show/hide the second select box based on the hidden elements value when it changed as a result of selecting the country (the third party JavaScript already updates the hidden element value with the newly selected country value). I've tried doing this in jQuery and just straight JavaScript API, however nothing seems to work. Just FYI, when the third party javascript rescripts my select box into div/span's and a hidden input field, the hidden input field does not have an id attribute, so I reference the element through its name (collected_data[7][0]). Here's the code I tried thus far:
<script type="text/javascript">
jQuery(document).ready(function(){
jQuery("input-country").change(function(e){
console.log("testA");
});
})
jQuery("input-country").change(function(e){
console.log("testB");
});
jQuery(document).ready(function(){
jQuery(document.forms['myForm']['collected_data[7][0]']).change(function(e){
console.log("testC");
});
})
jQuery(document.forms['myForm']['collected_data[7][0]']).change(function(e){
console.log("testD");
});
document.forms['myForm']['collected_data[7][0]'].onchange = function(){
console.log("testE");
};
document.getElementById('input-country').onchange = function(){
console.log("testF");
}
jQuery(document.forms['myForm']['collected_data[7][0]']).live('change',function(){
console.log("testG " + jQuery(this).val())
});
jQuery('input-country').live('change',function(){
console.log("testH " + jQuery(this).val())
});
jQuery(document).ready(function(){
jQuery(document.forms['myForm']['collected_data[7][0]']).live('change',function(){
console.log("testI " + jQuery(this).val())
});
})
jQuery(document).ready(function(){
jQuery('input-country').live('change',function(){
console.log("testJ " + jQuery(this).val())
});
})
</script>
You won't get "change" events when the hidden element is changed programatically by somebody's JavaScript code. Those are only generated by the browser when there's actually user action. What would be better would be for the 3rd-party JavaScript to explicitly call ".change()" (the jQuery method) on the hidden select.
A hidden element is clearly never going to be a target for user interaction.
'input-country' is not a valid selector. Further, the change event requires focus gain, value change, focus loss (blur)--hidden inputs will not have such a sequence of events, so you must manually trigger change on them when you change their values.