I am new to jQuery and hope someone here can help me with this.
I have a large HTML form with a hidden div ('#requestDetails').
Within this div there are checkboxes, radio buttons and selects with a certain class on a specific value ('.hiddenDefault') which is used to only apply a default value when they are visible.
Now I have a certain event that shows this div and another one that hides it again.
When showing the div I want to set the above default values.
When hiding it I want to reset the fields, incl. all input fields within that div (i.e. uncheck / unselect them and remove any default or entered values).
I have the following code which looks ok to me at first glance but I would like to know if this is proper / valid code, if I am missing anything here and if there is a better / faster way to achieve the same.
My jQuery:
$('[name=requestType]').on('change', function(){
if($(this).hasClass('triggerDiv')){
$('#requestDetails').find('.hiddenDefault').each(function(){
// set default values + show div
$(this).not('select').prop('checked', true);
$(this).not('input[type=checkbox], input[type=radio]').prop('selected', true);
});
$('#requestDetails').show();
}else{
$('#requestDetails').find('input, select').each(function(){
// empty / reset fields + hide div
$(this).find('input[type=checkbox], input[type=radio]').prop('checked', false);
$(this).find('input').not(':button, :checkbox, :hidden, :radio, :reset, :submit').val('');
$(this).find('select').prop('selected', false);
});
$('#requestDetails').hide();
}
});
Many thanks in advance for any help with this,
Mike
Just improving syntax or style of code you have written:
$('[name=requestType]').on('change', function(){
if($(this).hasClass('triggerDiv')){
// show div + set default values
$(this).not('select').prop('checked', true);
$(this).not('input[type=checkbox], input[type=radio]').prop('selected', true);
$('#requestDetails').show();
}else{
// hide div + reset fields
$('#requestDetails').find('input[type=checkbox], input[type=radio], input, select').not(':button, :checkbox, :hidden, :radio, :reset, :submit').val('').prop('checked', false);
$('#requestDetails').hide();
}
});
Sorry have not checked syntax, so correct me if I am wrong at it.
Not this will improve performance as well as you have written inside each.
Related
I have a top level select box that when a user makes a selection here, I want this value to be used for all the below select boxes relating to this top level box.
The problem I am having is that, if any one of the lower select boxes is disabled, I want the above process to ignore this select box as it has already been assigned a value.
Obviously, if the lower select box is enabled then I want to assign the top select value to it.
To disable the select list based on a particular value, I have used:
$("select[name=f03]").eq(index).attr('disabled', 'disabled');
Here is the jQuery that I have used but is not working:
var top_select = $("select[name=f07]").val();
$("select[name=f03]").each(function(index){
if $("select[name=f03]").eq(index).is(':enabled'){
$("select[name=f03]").eq(index).val(top_select);
}
});
From this code, it is the lower selects ([name=f03]) that I am trying to set only when it is enabled.
First I would disable select like this:
$("select[name=f03]").eq(index).prop('disabled', true);
Second, your function should be much simpler:
$("select[name=f03]").each(function(){
if ($(this).prop('disabled')) return;
$(this).val(top_select);
});
you should use jquery :enabled selector as follow
$("select[name=f03]:enabled").each(function(){
//execution
});
or
$("select[name=f03]:enabled").val("value");
here is jsfiddle example http://jsfiddle.net/kso2oqr5/1/
When you are disabling elements use .prop(property,value)
var top_select = $("select[name=f07]").val();
$('select[name="f03"]').val(function(){
if(!this.disabled){
return top_select;
}
});
DEMO
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.
I have a form where the user can select a generic auto-population based on checking a radio button. When the user checks the auto-populate radio button, the fields are auto populated with the data and then the fields become disabled.
In this first part of the function, I pass the auto-filled data:
$('#myOptions').click(function()
$('#value1').val("Auto-filled data");
$('#Value2').val("Auto-filled data");
$('#Value3').val("Auto-filled data");
In this second part, I am disabling the html inputs
// now i am disabling the html inputs:
$('#Value4').prop("disabled", true);
$('#Value5').prop("disabled", true);
$('#value6').prop("disabled", true);
Suppose I have another field with an ID of "Value7" in the form, that I would like to hide from the user interface as part of this function.
How can I hide the "Value7" input upon function triggering? I appreciate the help, I am very new to JavaScript, though I find it very exciting!
Using jquery:
To hide
jQuery('#Value7').hide() or jQuery('#Value7').css("display","none")
To show the element back
jQuery('#Value7').show() or jQuery('#Value7').css("display","block")
or pure js:
javascript hide/show element
Try this javascript:
if you want disable:
document.getElementById('#Value7').setAttribute("disabled","disabled");
if you want enable:
document.getElementById('#Value7').removeAttribute('disabled');
if you want to hide :
document.getElementById('#Value7').css("display","none");
if you want to show:
document.getElementById('#Value7').css("display","block");
I am not getting what are you trying to ask actualy .
Let me know if this helps -
$("Value7").hide()
My app has a form which uses checkboxes to sort results by type and area. There are 2 fieldsets, one for the types and one for the areas.
The area checkboxes are linked to areas of an imagemap so it too can be used to select multiple areas to sort by.
I have this javascript:
This links the area checkboxes and the areas of the imagemap so they both act as form inputs
var $area = $('area');
$area.click(function(){
var $checkbox = $('#' + $(this).data("areanum"));
$checkbox.attr('checked', !$checkbox.attr('checked')).button('refresh');
});
$('label').click(function () {
$area.filter('[data-areanum="' + $(this).attr('for') + '"]').trigger('click');
return true;
});
This breaks the type checkboxes (they won't register as being checked when the form is submitted), unless I change the bit:
$('label').click(function () {
$area.filter('[data-areanum="' + $(this).attr('for') + '"]').trigger('click');
return false;
});
to
$('label').click(function () {
$area.filter('[data-areanum="' + $(this).attr('for') + '"]').trigger('click');
return true;
});
(changed the last line to return true)
But this makes the checkboxes difficult to select, they respond to a single click if the tick area is clicked but only respond to a double click if the checkbox label is clicked.
I hope this makes sense, if any clarification is needed I'll try to word the problem better.
Thanks for any help.
I think you don't need the label click handler at all because you are just toggling the checkbox checked property by triggering the area click handler which will be taken care by label's default behavior itself when it's for attribute is set to the checkbox id.
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.