I have a query builder form that allows a user to enter values into fields that once complete allows them to pass the entered values to a search field. Not all the fields have to be completed by the user within the form.
sample of html
<div id="advanceSearchCriteria">
<div class="searchHeader">Person</div>
<div class="contentBorders" id="person">
<div class="searchdiv">
<span class="smLabel">Last Name</span><br />
<input type="text" name="lastname" value="" size="15" />
</div>
<div class="searchdiv">
<span class="smLabel">First Name</span><br />
<input type="text" name="namefirst" value="" size="15" />
</div>
<div class="searchdiv">
<span class="smLabel">Middle Name</span><br />
<input type="text" name="namemiddle" value="" size="10" />
</div>
<div class="searchdiv">
<span class="smLabel">Suffix</span><br />
<input type="text" name="suffix1" value="" size="5" />
</div>
</div>
</div>
Within jQuery I created a function to pass the values of the fields to an asp.net textbox control
function setAdvancedSearchString() {
checkField();
var txt = $("input[name='tbsearchterm']");
var fields = $("#advanceSearchCriteria :input").serializeArray();
jQuery.each(fields, function (i, field) {
if (txt) {
txt.val(txt.val() + field.name + ": " field.value + " ");
}
});
}
With the current approach this returns all input fields and their values. What I would like to have is only fields that contain a value entered by the user to be serialized and passed to search term. For example if the user only entered last name I would only like that fieldname and value returned (lastname: james)
I’ve tried to test for null on the var fields but my syntax is wrong or I am testing for null in the wrong location
So far I have tried the following:
var fields = if($("#advanceSearchCriteria :input") != null)
{
$("#advanceSearchCriteria :input").serializeArray();
}
but this seems to cause a compile error.
Can anyone provide some help on how to only serialize and return fieldnames and values that have a value entered?
Thank you,
You can use
attribute not equals selectorto select fields with text and you don’t have to use.serializeArray(). Check this (example):Extra
I used an anonymous function for setting the value of
txtand used array/join for string concatenation.