jquery show/hide on user selection and form validation - javascript

I have form with an 'Employment Status' section. If the user selects 'Employed' from a drop-down list (#employment_status), then the following jQuery code shows an additional div section (which starts off hidden) with more fields for the user to fill out:
<script type="text/javascript">
var employ = jQuery('#employment_status');
var select = this.value;
employ.change(function() {
if ($(this).val() == 'Employed' ){
$('#employed').show(2000, 'easeOutExpo');
} else $('#employed').hide(2000, 'easeOutExpo');
});
</script>
This works if the user manually selects 'Employed'. However if the user selects 'Employed', submits the form, and there are validation errors which show up on the form (using in my case PHP which re-inserts all the values in the form and makes 'Employed' the 'selected' option in the dropdown), the 'Employed' section will come back closed. The only way to show the div section is to fiddle around with another value and choose 'Employed' again manually.
Is a solution to making the form come back with this div open if the 'selected' value is Employed.

try this
var employ = jQuery('#employment_status');
// check when form load
if ($('#employment_status').val() == 'Employed' )
{
$('#employed').show(2000, 'easeOutExpo');
}
else
{
$('#employed').hide(2000, 'easeOutExpo');
}
employ.change(function() {
if ($(this).val() == 'Employed' ){
$('#employed').show(2000, 'easeOutExpo');
} else $('#employed').hide(2000, 'easeOutExpo');
});

One possible solution is to trigger the change event manually after the handler is registered
var employ = jQuery('#employment_status');
var select = this.value;
employ.change(function () {
if ($(this).val() == 'Employed') {
$('#employed').show(2000, 'easeOutExpo');
} else {
$('#employed').hide(2000, 'easeOutExpo')
};
}).change(); //trigger the change event manuall to set the initial state

Related

Jquery Show Hide div on dropdown change not working properly while Updating

Problem: I am using Jquery for Show / Hide div on dropdown change on my application , when I am creating new Form its working better, but when i update it, the form getting collapsed to normal view and I'm not getting the one which I should view , so that is making me to change the drop down option again to view the fields which i set to show.
My JQuery:
<?php
$this->registerJs('
$(document).ready(function(){
$(\'.ordinary\').hide();
$(\'.special\').hide();
$(\'#company-typeofcompany\').change(function () {
var x = $(this).val();
if (x === "ordinary") {
$(\'.ordinary\').show();
$(\'.special\').hide();
}
else
{
$(\'.special\').show();
$(\'.ordinary\').hide();
}
});
});', \yii\web\View::POS_READY);
?>
I guess on update you have to check the condition of the dropdown value and if it is ordinary you have to show the normal and hide the special and viceversa for another value. The code might be
$(document).ready(function(){
$('.ordinary').hide();
$('.special').hide();
if ($('#company-typeofcompany').val() == "ordinary") {
$('.ordinary').show();
$('.special').hide();
} else {
$('.special').show();
$('.ordinary').hide();
}
$('#company-typeofcompany').change(function () {
var x = $(this).val();
if (x === "ordinary") {
$('.ordinary').show();
$('.special').hide();
} else {
$('.special').show();
$('.ordinary').hide();
}
});
});

Having issue with focus and blur function

I have a Form where there are three field and two buttons. FIDDLE
Clicking on Add optional Email Address button adds a new Email field which is fine. My issue is with Save Button. I am wanting the save button will remain disable until user click on the field or add any value in the input field.
So,
if a user click on any of the input field Save button will become
active
if a user put a value it will remain active.
if user clicks on the input but didn't give any value it will Change
to disable again.
Same for the New added input by Add optional Email Address
On my code it's not going back to disable state if no value given on the input after clicking and not working for newly added input. I am not sure the reason. Any help will save my day.
JS
$("body").on('focus', '.user-input input', function() {
$(".update-change").removeAttr('disabled');
}).blur(function() {
if ($("").val() == '') {
$(".update-change").attr('disabled', 'disabled');
}
});
$('.update-list-confirm').click(function(){
$(".update-change").attr('disabled', 'disabled');
});
// Add email
$("body").on('click', '.add-new-email', function() {
var newemail = '<div class="form-group"><em class="pull-right">Optional</em><input type="email" name="userEmail" class="form-control" id="" placeholder="mymail#mail.com"></div>';
$(newemail).insertBefore(this);
});
Try this to handle blur on the same input element
$("body").on('focus', '.user-input input', function() {
$(".update-change").removeAttr('disabled');
}).on ('blur', '.user-input input', function() {
if ($(this).val() === '') {
$(".update-change").attr('disabled', 'disabled');
}
});
Is this a typo? Change it with correct values:
if ($("").val() == '') {
I guess it should be:
if ($('[name="userEmail"]').val() == '') {
To disable the SAVE button if ANY of the text fields are blank, you should use this snippet of code:
$(':text').focusout(function () {
$(':text').each(function (i) {
if (this.value === '') {
$('.update-change').attr('disabled', 'disabled');
}
});
});
This way, when the SAVE button is clicked (and the :text fields are no longer in focus), each :text field is checked for a value.

What is wrong with my JavaScript code? (Search bar)

I have some code here in JS and I can't figure out why it isn't doing what I want it to do. Basically, I have a search bar that should write "Search..." it in. When the user clicks on it, the text goes away and the bar goes blank. If the user clicks away without filling any text in, the "Search..." text returns.
Otherwise, the text the user enters stays in the bar. Up until this point my code works fine. The issue is this; when the user inputs something AND THEN takes it away, the bar remains blank, whereas the "Search..." text should return. (Notice: This does not occur if the user simply clicks on the bar and then clicks away; the default text returns as it should. It only happens if the users enters something and then takes it away.)
I can not figure out why this is happening. Any help would be greatly appreciated. Here is my JS code:
$(document).ready(function () {
var search_default = 'Search...';
$('input[type="search"]').attr('value', search_default).focus(function () {
if ($(this).val() == search_default) {
$(this).attr('value', '');
}
}).blur(function () {
if ($(this).val() == '') {
$(this).attr('value', search_default);
}
});
});
Use .val(value) instead of attr('value',value)
$(document).ready(function () {
var search_default = 'Search...';
$('input[type="search"]').val(search_default).focus(function () {
if ($(this).val() == search_default) {
$(this).val('');
}
}).blur(function () {
if ($(this).val() == '') {
$(this).val(search_default);
}
});
});
If you can edit the HTML, this is how i would do it:
JSFIDDLE DEMO - EDITED HTML
If you cannot edit the HTML, you would need to create the data-default attribute
JSFIDDLE DEMO 2 - NON EDITED HTML
Add a data-default tag to the element
<input type="search" data-default="Search..." value="Search...">
And the jQuery
$(document).ready(function(e){
// when you focus on the search input
$('input[type=search]').on('focus',function(e){
// if the value is the same as the default value
if( $(this).val() == $(this).attr('data-default') )
{
// make the value blank
$(this).val('');
}
// when you move out of the search input
}).on('blur',function(e){
// if there is no value (blank)
if( !$(this).val() )
{
// add back the default value
$(this).val( $(this).attr('data-default') );
}
});
});

Javascript iterate through all checkboxes on submit, and set attribute if changed from original value

I am trying to make a javascript function similar to the following, except it will iterate through all the checkboxes when the user clicks the submit button:
$('.checkboxstatus').click(function(){
this.setAttribute('checked',this.checked);
if (this.checked && $(this).data("def") == 0){
//checkbox has changed
this.setAttribute('changed', 'yes');
}
else if(!this.checked && $(this).data("def") == 'checked')
{
//checkbox has changed
this.setAttribute('changed', 'yes');
}
else{
//no change in checkbox
this.setAttribute('changed', 'no');
}
});
When the user clicks submit, the function should be called and it should iterate through all checkboxes and see if the checkbox is checked and see if the data-def is checked or 0. If the checkbox is checked and data-def="checked" then nothing should happen. If the checkbox state is different from the data-def then an attribute ("changed") should be added to that checkbox with value of "yes". Any suggestions on how to go about this?
Your question almost gives you the answer. You need to attach a "submit" event handler to the form, then grab all input[type=checkbox] and set the "changed" attribute accordingly.
I'm not sure I get this, but the usual way to do something like this would be to set an initial state in data, then on submit, prevent the submit action, check all the checkboxes against that initial state data variable, and see if anything changed, if it did, trigger the native submit handler ?
var boxes = $('input[type="checkbox"]').each(function() {
$(this).data('initial_state', this.checked);
});
$('form').on('submit', function(e){
e.preventDefault();
var same_same = true;
boxes.each(function() {
if ( $(this).data('initial_state') !== this.checked ) { // has changed ?
$(this).data('changed', true);
same_same = false;
}
});
if ( ! same_same ) { // diffelent
this.submit();
} else {
alert('same same, but not diffelent!');
}
});

how to disable a dropdown item after its been selected

i have a regular combobox and i am listening to the change event and sticking the selected value in an html table. this all works fine but there is one issue. Right now, the user can select the same item more than once (which i dont want to allow).
At the point of where an item is selected, i want to:
Capture the value and stick it in the table (which i am doing now and code is below)
<script type="text/javascript">
$(document).ready(function() {
$('#categories').change(function() {
if (this.selectedIndex != 0) {
addRowToTable(this.value);
}
});
}
And i am trying to figure how to do #2 and #3 below . .
reset the selectedindex back to 0 (which says "Please select . .")
Not allow that selection to be selected again (and any visual representation on disabling that dropdown item).
Number 1 is pretty simple:
$('#categories option:first').get(0).selectedIndex = 0;
You can also use the value of the option against the dropdown list like so:
$('#categories').val('myOptionValue');
To prevent an item from being selected a second time, I would remove it from the dropdown list with something like this:
$('#categories option[value=valueToRemove]').remove();
cballou's answer sets #rel="disabled" on the select element, which causes the "single selection allowed bug".
I would tweak it to look like the below code. Also, I'd recommend setting a class instead of using the rel attribute. That way you add styles (browser permitting) that indicate to the user that the option is disabled.
CSS:
#categories .disabled { background:#c00; }
JS:
$(document).ready(function() {
$('#categories').change(function() {
var selectedIndex = this.selectedIndex,
selection;
if ( selectedIndex !== 0 ) {
selection = $(this.options[selectedIndex]);
if( !selection.hasClass('disabled') ) {
addRowToTable(this.value);
selection.addClass('disabled');
}
}
// reset selected index
$(this).val('');
});
});
OK if i were you i wouldnt use a Drop down box for this... i would use multiple <select multiple="true"> which is going to allow you to select multiple items at a time by using ctrl+click (cmd+click on mac), then i would have an add button to click when done. this would fire the js taht would grab all the selected options put em in your table or what have you and then then remove them from the select box.
http://www.w3schools.com/TAGS/att_select_multiple.asp
You could add a rel="disabled" attribute to the option and check for it like so:
$(document).ready(function() {
$('#categories').change(function() {
if (this.selectedIndex != 0 && $(this).attr('rel') != 'disabled') {
addRowToTable(this.value);
$(this).attr('rel', 'disabled');
}
});
});
If your first option (selectedIndex 0) has an empty value, you can easily reset like so:
$(document).ready(function() {
$('#categories').change(function() {
if (this.selectedIndex != 0 && $(this).find('option:selected').attr('rel') != 'disabled') {
addRowToTable(this.value);
$(this).find('option:selected').attr('rel', 'disabled');
}
// reset selected index
$(this).val('');
});
});

Categories

Resources