简体   繁体   中英

If the textbox val is empty then gets added to array in javascript

I am trying to save student details in the database. In the front end i have a table which takes the student id, name and phone number .

<table>
<tr>
<td align="center">1</td>

<td>Name</td>

<td><input type="text" value="sname"></td> 

<td>Mobile</td>

<td><input type="text" value="smob"></td> 
.....
</tr>
</table>

Now if i save more than one student detail i am adding to array but the mobile is not mandate .

Now while saving into array if mob is empty it takes as empty string

 var i=0;
  jQuery("table tr".each(function()
  {

  name=jQuery(this).find('name').val();

  mob=jQuery(this).find(smob).val();

  name[i]=name;

   mob[i]=mob;

  });

Now if the mob say i am saving three details and if mob is empty

then the array mob[i]=["",1,""];

How to add to array if it is not empty such that the mobile number corresponds to the student

One way how to solve this problem is to create an array of Students. Note that there are several syntax errors in the code above like 1.

jQuery("table tr" 

should be

jQuery("table tr")

and 2. the jquery find should be based on some identifier eg attribute, id, class, index 3. you are resusing the variables name and mob for different purposes first as an array then as a variable within the loop which causes the values to be overwritten.

you can find an example solution at http://jsfiddle.net/TZ4PH/

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM