0

I have the following code which converts all field values of a form to a single object. However, it is not converting hidden fields that are dynamically loaded (but it would convert them if their values are hardcoded).

According to my research, serializeArray() should cover hidden fields as long as they have names. And mine do have names. So I can't figure out what's wrong here.

serializeArray():

var data = {}; 
$("#form1").serializeArray().forEach(function(x){
   data[x.name] = x.value;
 });
console.log(data);

Dynamic loading of hidden field values using JQuery

$("#field1").val("400"); //400 is just an example here   

Form:

<form id="form1">
    <!-- Not serialized -->
    <input type="hidden" name="field-value.hidden.1" id="field1" value=""/> 

    <div class="container">
        <div class="row">
            <div class="col-sm-12">
                <!-- Works fine -->
                <textarea id="field2" name="field-value.show.1" rows="3" cols="10"></textarea> 
            </div>
        </div>
    </div>
</form>

Summary of issue:

serializeArray works if input looks like:

<input type="hidden" name="field-value.hidden.1" id="field1" value="400"/> 

but not if it is:

<input type="hidden" name="field-value.hidden.1" id="field1" value=""/>

$("#field1").val("400"); 
OneMoreQuestion
  • 1,544
  • 2
  • 19
  • 43

1 Answers1

0

One workout I just discovered from reading here: (https://stackoverflow.com/a/25402639/4996722)

$("input[id=field1]").val("400"); would correctly put the value in there. However, this may be a JQuery bug as there is no good reason behind why $("#field1").val("400") does not work as they are the same thing.

OneMoreQuestion
  • 1,544
  • 2
  • 19
  • 43