JQuery serializeArray does not include selects without selected options - javascript

I use the serializeArray() method to get the HTML form as JS object. When the form has a select control with "multiple" options but no option is selected the object is not serialized.
Here is an example: https://fiddle.jshell.net/tfzxmr9d/1/
It works fin when it has one or more values. It should return an object with the control name and empty or null value. Is it working as expected ?

It seems you forgot about $(function(){}); ready syntax. Your code may looks like that. Because jQuery in your case maybe not ready.
$(function(){
function showValues() {
var fields = $( ":input" ).serializeArray();
$( "#results" ).empty();
jQuery.each( fields, function( i, field ) {
$( "#results" ).append( field.name + ": " + field.value + "<br>" );
});
}
$( ":checkbox, :radio" ).click( showValues );
$( "select" ).change( showValues );
showValues();
});

This is to be expected with no valid results. To change this behavior add this line right after fields is initialized:
fields = fields || [{name: 'multiple', value: 'Null'}];

if(!fields.some(function(element){return element.name === "multiple"})){
fields.push({name: 'multiple', value: 'Null'});
}
https://fiddle.jshell.net/tfzxmr9d/2/ I can't think of a way around checking the whole array for a 'multiple' so there you go.
But you should probably modify your server-side code to accept the default output since that's the normal way HTML forms are serialized.

Related

loop over forms to find if a field has a data variable

I am trying to loop over all forms on a page, then see if they have a "missing-field" data variable. Once found, I then want to highlight that field.
Currently I have it working to detect if the data var exists, but now I can't quite get it right where I see if a field with that name exists. Pointers appreciated.
Here is what I have so far:
$( "form" ).each(function( index )
{
if (undefined !== $( this ).attr('data-missing') && $( this ).attr('data-missing').length)
{
field_name = $( this ).attr('data-missing');
if ($( this + " input:text[name="+field_name+"]").length)
{
alert('this part isnt working...');
}
}
});
To query any DOM element with a specific name in JQuery, you can just do this:
$('[name="field_name"]')
To query an element which is a child of another element, you can use this syntax:
$('parent > child')
So your code would be:
...
field_name = $( this ).attr('data-missing');
if ($( `${field_name} > input:text[name="${field_name}"]`).length)
{
alert('Value missing');
}
field_name needs to be a selector of some sort. I don't know what the contents of data_missing are, but they'd need to be an id (like #form1) or something similar.

Javascript for each textbox depend on drop down list

I make input form using static row in 7 rows. How can I get selected value in each textbox when drop down list selected? I tried to use jQuery to do it, but my code is getting error (all textbox changed). So, below is my jQuery code:
<script>
$(document).ready(function() {
$('[name="nm_pot_part_shortage[]"]').on('change', function() {
$('[name="nm_maker[]"]').val($(this).val());
});
});
</script>
Image of my form:
You must escape bracket notation by using double slashes for selector having name like $('[name="nm_pot_part_shortage\\[\\]"]'), otherwise you will get an error, see following code :
$( '[name=nm_pot_part_shortage\\[\\]]' ).on( 'change', function () {
// get current value
var selectVal = $( this ).val();
// find the input by traversing up the parent first using .closest()
// and use .find() to find particular input exist on the same rows with
// select element, so this never go down to match another input exist on
// another rows
$( this ).closest( 'tr' ).find( '[name=nm_maker\\[\\]]' ).val( selectVal );
});
DEMO(example given were using table)
Better case is just give all the select and input with the same class name for each element. As example give class name myselect to select element and myInput for input element, at the end JS code would be :
$('.mySelect').on('change', function () {
var selectVal = $( this ).val();
$( this ).closest( 'tr' ).find( '.myInput').val(selectVal);
});
Native Javascript:
1) Give each dropdown an ID. This can be done in the HTML or dynamically in javascript.
2) Assign a function to each dropdown for an onclick event.
3) Retrieve the value as such:
function dropdownClicked(){
var ID = this.id;
var element = document.getElementById(ID);
var value = element.value;
}

How to get an attibute from another attribute in the same element

What I'm trying to achieve is get an attibute from another attribute in the same element. For example:
<script>
$("#step1").click(function() {
// Get the attribute 'next' and get its value.
});
</script>
<button id="step1" next=".openNextModal">
Your need to use attr()
<script>
$("#step1").click(function() {
// Get the attribute 'next' and get its value.
var next = $( this ).attr( 'next' );
//if you are looking for next attribute value of the next element
console.log( $( next ).attr( 'next' ));
//if this is an input element and you are looking for its value
console.log( $( next ).val());
//if this is an not input element and you are looking for its html
console.log( $( next ).html());
});
</script>
Try like following.
$("#step1").click(function() {
console.log($(this).attr('next'));
});

Jquery get the value of the input when changing

I would like to get the value of an input and return it to a span. I would like to update the span each time the input is changing. The problem is that i will use it for a colorpicker so the user will not usualy write the color value(maybe paste it). So everytime the input textfield will be updated by the colorpicker js i want to update my own field.
I created a simple code to help you understand what i want to do.
Pressing the + you will change the value of the input field and i would like to get that value and print it in the span. Thank you.
HTML ::
<div>
<input type="text" class="mariinsky" /><button id="inside">+</button>
</div>
<button id="outside">Button</button><br />
input value = <span></span>
JS ::
var i = 0;
jQuery('button#outside').click(function() {
jQuery('div').toggle();
});
jQuery('button#inside').click(function() {
jQuery( ".mariinsky" ).val(i);
i++;
});
$( '.mariinsky' ).change( function() {
var bolshoi = jQuery( ".mariinsky" ).val();
jQuery( 'span' ).text(bolshoi);
});
http://jsfiddle.net/existence17/9V8ZU/1/
Add .change() to the end of your '+' handler:
jQuery('button#inside').click(function() {
jQuery( ".mariinsky" ).val(i).change();
i++;
});
That will force the change event to fire and then your code will update the span.
For live DOM changes, use the jQuery on function - the following code would work in your case:
var i = 0;
jQuery('button#outside').click(function() {
jQuery('div').toggle();
});
jQuery('button#inside').click(function() {
jQuery( ".mariinsky" ).val(i);
i++;
});
$( 'button#inside' ).on('click', function() {
var bolshoi = jQuery( ".mariinsky" ).val();
jQuery( 'span' ).text(bolshoi);
});
jQuery doesn't automatically trigger events through code. You need to do so manually using the .trigger() method.
Adding one line did it for me: jQuery('.mariinsky').trigger("change").
Here's a working example: http://jsfiddle.net/9V8ZU/2/
Also a useful question for reference: How to trigger jQuery change event in code
please use this :
$( '.mariinsky' ).on('keypress keyup keydown click copy cut paste', function() {
var bolshoi = jQuery( ".mariinsky" ).val();
jQuery( 'span' ).text(bolshoi);
});
Fiddle example
all the rest of the provided answers aren't covering the entire options.

jQuery UI Autocomplete

I am using jQuery UI's autocomplete plugin and everything is well and good except for that fact that when a user clicks the value they want the function I have assigned to the "select:" method fires before the value of the field is changed. So if I type "Foo" in the input field, then click the autocomplete match for "Foo Bar" the function detects the value as what was typed (in this case "Foo") as opposed to the value which was selected from the autocomplete list. Once the function fires (in this case I just have an alert box popup with this.value) the value of the input field is set to the value selected via the autocomplete list. This problem does not occur if the user selects the option with the keyboard (arrow keys->tab), only when the mouse is used.
$(function()
{
var aEmps =
[
<?php
echo $sEmps;
?>
];
$("#slast").bind( "keydown", function( event ) {
if ( event.keyCode === $.ui.keyCode.TAB &&
$( this ).data( "autocomplete" ).menu.active )
{ event.preventDefault(); }
})
.autocomplete({
source: aEmps,
select: function(event, ui)
{
var aName = $(this).val();
alert(aName);
}
})
});
Since most users will be interacting with this using their mouse I have to find a way to get the value set before firing the "select:" function. I believe I can accomodate for this by adding a condition to the statement prior to the auto complete but I need some help finding the right syntax.
Looking at the documentation, it looks like the select event is fired as the selection is being updated, not after the selection is updated. Try using the change event instead of select, and see if that solves your problem.
After trying a number of approaches I found that by simply binding the callback function to the close event works very well. I added some error handling to catch values that aren't selected from the list and I am off and running!
Here is the updated code:
$(function()
{
var aEmps =
[
<?php
echo $sEmps;
?>
];
$("#slast").bind( "keydown", function( event ) {
if ( event.keyCode === $.ui.keyCode.TAB &&
$( this ).data( "autocomplete" ).menu.active )
{ event.preventDefault();}
})
.autocomplete({
source: aEmps,
close: function(event, ui)
{
alert(this.value);
}
})
});

Categories

Resources