Event Handler for Input values and select option together - javascript

I have multiple input values with one select box option and validating and capturing all data based on keypress event. My issue is get all data input fields and select box and send using keypress event
To find all input values
var all_details = $('.myform');
var all_inputs = all_details.find('input');
var all_details_complete;
to get select values
var Country = $('#country').children("option:selected").val();
Adding few more additional data
var some_data = {
Country: Country, //select box title displaying on image
ReceiveOffers: 0
};
Bind event! With following function I am getting all input field data except select box data. how can I add select change event and have tried following?
all_inputs.on('keypress onchange', function() {
all_details_complete = false;
_.each(all_inputs, function (input) {
var $input = $(input);
all_inputs[$input.attr('name')] = $input.val();
if ($input.val() === '') all_details_complete = false;
});
if (all_details_complete) {
// post data successfully
}
});

That is because there is no onchange event, but a change event instead:
all_inputs.on('keypress change', function() {
// Rest of the code here
};
However, for ease of standardization it's way easier to simply listen to the input event:
all_inputs.on('input', function() {
// Rest of the code here
};

Related

Why focusout event is not fired

I created code for dropdown menu instead of classic select menu which I am not able to style. I have last step to remove dropdown list if focusout event is fired, but I ahve this problem. It is not working for one element in my code.
I am thinking a long time why it is not fired focusout event on this element inputSelectSubCat = $("input[name=subcategory]"); or generally var inputSelect = $('.add-item__input-select');.
In firefox developer console it is added action for this event, but it is never fired.
Thank you very much for your advices.
This is my code:
/* SELECT CATEGORIES AND FILTER CONNECTIONS*/
// Declare variables
var inputSelectCat = $("input[name=category]"),
inputSelectSubCat = $("input[name=subcategory]"),
arrowDown = inputSelectSubCat.next(),
catNameOld;
// Defaultly setup subcategory input as disable until category is not chosen
inputSelectSubCat.addClass('stop');
// Disable placeholder hidding - disable focus event
inputSelectSubCat.on('mousedown', function() {
event.preventDefault();
});
// Defaultly hide arrowdown of input subcategory until category is not chosen
inputSelectSubCat.next().hide();
inputSelectCat.on('focusin', function() {
catNameOld = $(this).val();
});
localStorage.clear();
// If change value of category then change options of subcategory
inputSelectCat.on('focusout', function() {
var catNameNew = $(this).val(),
arrowDown = inputSelectSubCat.next();
// Send cat id to add.php to change select options in html according to cat id
$.ajax({
url: 'add.php',
type: 'post',
data: {
cat_name_js: catNameNew
}
}).done(function(html) {
var subCatMenuNew = $(html).find('select[name=subcategory]'),
subCatMenuCurrent = $('#section-info').find('select[name=subcategory]');
// Replace current select by new one - data for dropdown list are loaded from select
subCatMenuCurrent.html(subCatMenuNew);
})
// Allow subcategory input always if category is chosen and value is not empty
if (catNameNew !== '') {
arrowDown.show();
inputSelectSubCat.removeClass('stop');
}
// If different category is chosen, then clear input value
if (catNameOld !== catNameNew) {
inputSelectSubCat.val('');
}
});
// If change value of category then change options of subcategory
inputSelectSubCat.on('focusout', function() {
$('#filters, #section-filters').show();
});
/* SELECT REPLACED BY DIV JS */
var inputSelect = $('.add-item__input-select');
// Add new div with options after click on select
inputSelect.on('click', function(event) {
event.preventDefault();
var currentNewDropdown = $(this).next(),
currentInput = $(this),
currentSelect = $(this).parent().find('select');
// Do not allow to add dropdown list for subcategory if it has class 'stop'
if ( !currentInput.hasClass('stop')) {
// Check if new div dropdown already exists if not add new one
if ( !currentNewDropdown.hasClass('add-item__custom-select-box') ) {
var newDropdown = $('<div/>') // create new div element
.addClass('add-item__custom-select-box') // with class NewDropdown
.insertAfter($(this)); // and append it to page
}
}
// If select was already clicked on, then do not create new dropdown list
if ( !currentInput.hasClass('added') ) {
// Check each option value and attach it to new dropdown as div
currentSelect.find('option').each(function(index, element) {
var option = $(this); // this is the option from the original select
currentNewDropdown = $(this).parent().next();
// If option is disabled do not append it to new dropdown list
if (!option.prop('disabled')) {
// Create dropdown list as copy of original select list
var newOption = $('<div/>') // create new div element
.addClass('add-item__custom-select-box-items') // with class NewDropdown-item
.html(option.html()) // copy content from original option
.data('value', option.val()) // copy value from original option
.appendTo(newDropdown); // append it to the new dropdown
}
})
// Show new dropdown options after click on select
if ( !currentInput.hasClass('stop')) {
currentNewDropdown = $(this).next();
currentNewDropdown.show();
currentInput.addClass('added');
}
}
});
// Remove dropdown list if focusout without value chosen
inputSelect.on('focusout', function() {
console.log('2');
var newDropdown = $(this).parent().find('.add-item__custom-select-box'),
inputValue = $(this).val();
newDropdown.remove();
inputSelect.removeClass('added');
inputSelect.addClass('black-text');
});
// Add value of clicked element to original option
$('.add-item__input-wrapper').on('mousedown','.add-item__custom-select-box-items', function() {
var clickedOptionText = $(this).text(), // Get choosen otion text
clickedOptionVal = $(this).data('value'), // Get choosen option value
currentInput = $(this).parent().prev(),
currentSelect = $(this).parent().parent().find('select'),
newDropdown = $(this).parent();
currentSelect.val(clickedOptionVal); // Set up value of original select
currentInput.val(clickedOptionText); // Show chosen value in input
newDropdown.remove();
inputSelect.removeClass('added');
inputSelect.addClass('black-text');
});

Add to HTML input array

I have a hidden input field like this in jade:
input(name='saintForm[quotes][]', type='hidden')
I want to use jquery to add to this array from a dynamic unordered list, but not sure how. Here's my failing attempt:
$('#form').on('submit', function(e){
e.preventDefault();
$('.quote').each(function (i){
var item = $(this).text().replace(' (x)','');
$("input[name='saintForm[quotes][]']").push(item);
});
this.submit();
});
If you're just adding a value to the default form functionality you could create an input with a value.
// grab your form and wrap it in jQuery
var myForm = $('#form');
// list teo the submit event
myForm.on('submit', function(e) {
e.preventDefault();
$('li.quote').each(function() {
$('<input />', {
type: 'text', // input type
name: 'saintForm[quotes][]', // the name of the form input
value: $(this).text() // the text from the current list-item
}).appendTo(myForm); // append each input to the form
});
myForm.submit(); // submit the form
});
You can of course send all sorts of arbitrary data to the server easily with AJAX but if you are just using the normal form submit I guess this is a good way to do it.

How can I add a 'change' event listener for a styled select?

Obviously, if I have a 'select' element, I can add an event listener for changes using some basic JS:
document.querySelector('select').addEventListener('change', function(ev){
console.log('Changed', ev.target.value)
})
Click the 'select' element, modify the value, the log fires. Simple stuff.
However I'm working on a library for styled select boxes - like chosen or select2 without the jQuery dependency.
In my library, clicking the styled select box changes the .value of the real select box:
query('select').value = newValue;
I can see this is working if I make the real select box visible.
However, changing the value of the select box through JS doesn't trigger the select boxes 'change' event.
Is there a way I can change the select boxes value though JS and still have change events attached to the select box fire?
Javascript
function fireEvent(element, event) {
if (document.createEventObject) {
// dispatch for IE
var evt = document.createEventObject();
return element.fireEvent('on' + event, evt)
} else {
// dispatch for firefox + others
var evt = document.createEvent("HTMLEvents");
evt.initEvent(event, true, true); // event type,bubbling,cancelable
return !element.dispatchEvent(evt);
}
}
document.querySelector('select').addEventListener('change', function (ev) {
console.log('Changed', ev.target.value)
});
btn.onclick = function () {
select.selectedIndex = 2;
var obj = document.querySelector('select');
fireEvent(obj, 'change');
}
User call
var yourPlugin=new CustomSelect(options);
yourPlugin.value("3");
Plugin function
function value(val) {
if (!val) return select.value;
select.value = val;
fireEvent(select, 'change');
}
DEMO
Just an idea: Trigger the event by yourself after changing the value:
var el = query('select');
el.value = newValue;
el.dispatchEvent(new Event('change'));
Based on #Hamix's excellent answer, and some advice from MDN about createEvent() being out of date, I eventually went with:
var changeEvent = new Event('change');
realSelect.dispatchEvent(changeEvent);
Here's a demo - again based on #Hamix's jsfiddle so go give him an upvote.

How to validate a memorized value in an input box

I have the following code:
$(":input").bind("keyup change", function(e) {
var comboVal = $('.emailrequerido1').val()+$('.emailrequerido2').val()+$('.emailrequerido3').val()+$('.emailrequerido4').val()+$('.emailrequerido5').val();
if(comboVal == 'nullnull' || comboVal == ""){
$("#enviarForm").attr('disabled', true);
}else{
$("#enviarForm").removeAttr('disabled');
}
});
What I am trying to accomplish is that when you select a memorized value from the input box by double clicking in the box a history of inputs shows (these values are saved by the browser (I believe)) and if you choose one of these and the field has that text you selected the button should enable.
Here is a JSFiddle example: JSFiddle example
In the example I added a value to the first field since these dont memorize as I expalined before to show a demonstration of what I mean.
I have cleaned up the code a bit: http://jsfiddle.net/kam5B/1/
I've swapped the classes and ids so that the ids are unique, and the classes are common.
Here is a checkEmails function that runs the validation and enables/disables the checkbox.
checkEmails is run every time an input changes, and when the page loads the first time:
$(document).ready(function () {
function checkEmails() {
var nonempty = $('form .email_contactopadrino').filter(function() {
return $(this).val() != '';
});
if (nonempty.length) {
$('#enviarForm').removeAttr('disabled');
}
else {
$('#enviarForm').attr('disabled', true);
}
};
$('form').on('keyup change', '.email_contactopadrino', checkEmails);
checkEmails();
});

How to know with jQuery that a "select" input value has been changed?

I know that there is the change event handling in jQuery associated with an input of type select. But I want to know if the user has selected another value in the select element ! So I don't want to run code when the user select a new element in the select but I want to know if the user has selected a different value !
In fact there are two select elements in my form and I want to launch an ajax only when the two select elements has been changed. So how to know that the two elements has been changed ?
You can specifically listen for a change event on your chosen element by setting up a binding in your Javascript file.
That only solves half your problem though. You want to know when a different element has been selected.
You could do this by creating a tracking variable that updates every time the event is fired.
To start with, give your tracking variable a value that'll never appear in the dropdown.
// Hugely contrived! Don't ship to production!
var trackSelect = "I am extremely unlikely to be present";
Then, you'll need to set up a function to handle the change event.
Something as simple as:-
var checkChange = function() {
// If current value different from last tracked value
if ( trackSelect != $('#yourDD').val() )
{
// Do work associated with an actual change!
}
// Record current value in tracking variable
trackSelect = $('#yourDD').val();
}
Finally, you'll need to wire the event up in document.ready.
$(document).ready(function () {
$('#yourDD').bind('change', function (e) { checkChange() });
});
First of all you may use select event handler (to set values for some flags). This is how it works:
$('#select').change(function () {
alert($(this).val());
});​
Demo: http://jsfiddle.net/dXmsD/
Or you may store the original value somewhere and then check it:
$(document).ready(function () {
var val = $('#select').val();
...
// in some event handler
if ($('#select').val() != val) ...
...
});
First you need to store previous value of the selected option, then you should check if new selected value is different than stored value.
Check out the sample!
$(document).ready(function() {
var lastValue, selectedValue;
$('#select').change(function() {
selectedValue = $(this).find(':selected').val();
if(selectedValue == lastValue) {
alert('the value is the same');
}
else {
alert('the value has changed');
lastValue = selectedValue;
}
});
});​
You can save the value on page load in some hidden field.
like
$(document).ready(function(){
$('hiddenFieldId').val($('selectBoxId').val());
then on change you can grab the value of select:
});
$('selectBoxId').change(function(){
var valChng = $(this).val();
// now match the value with hidden field
if(valChng == $('hiddenFieldId').val()){
}
});
$("select").change(function () {
var str = "";
$("select option:selected").each(function () {
str += $(this).text() + " ";
});
$("div").text(str);
})
.change();
http://docs.jquery.com/Events/change

Categories

Resources