javascript - value of the select option going to be lost when it return a erro on the form -
i know sounds similar,but couldnt find useful article. have select option html tag in website im used select categories.but end user selected values disappear(come first value ever has been selected). in example have tag
<select name="type" > <option value="">select category</option> <option value="car">car</option> <option value="van">van</option> <option> </select>
in example first select box selected when browser loading first time , user can select value , must not empty.and if user select "van" , has been fill out other fields in form if return error before insert values database, select box value has been reset first value ("select category"). want prevent happening anymore.i hope of expert can me @ point.thank !
i think understand question.
visitors web page complete number of data fields, 1 of select control. however, if there problem submitting data database, values erased when page re-displayed user. correct?
if so, there couple of ways solve it.
(1) client-side field validation: before form submitted, test values of fields sure valid before allowing form submission continue. like:
javascript/jquery:
$(document).ready(function(){ $('#myformid').submit(function(e){ var first_name = $('#firstname').val(); var last_name = $('#lastname').val(); if (firstname=="" || lastname==""){ alert('please complete fields') e.preventdefault(); } }); }); //end document.ready
(2) ajax. ajax method allows submit data server (similar using form) without leaving/refreshing page. if there problem, page can updated telling user fix -- , user's changes preserved. can use <form>
container ajax, not necessary. can use divs , ajax work same. in fact, when using form, must use event.preventdefault()
stop form trying leave page (its default behaviour).
javascript/jquery:
$(document).ready(function(){ $('#myformid').submit(function(e){ var first_name = $('#firstname').val(); var last_name = $('#lastname').val(); if (firstname=="" || lastname==""){ alert('please complete fields') e.preventdefault(); } }); $('#myformid').submit(function(e){ var first_name = $('#firstname').val(); var last_name = $('#lastname').val(); if (firstname=="" || lastname==""){ alert('please complete fields') e.preventdefault(); } $.ajax({ type: 'post', url: 'add_the_data.php', data: 'fn=' +firstname+ '&ln=' +lastname, success: function(d){ if (d == 1){ //success $('#firstname').val(''); $('#lastname').val(''); alert('form submission successful'); }else //fail alert('data not submitted. please try again.') $('#firstname').focus(); } } }); }); //end submit }); //end document.ready
add_the_data.php
<?php $fn = $_post['fn']; $ln = $_post['ln']; //do database entry here $out = add_the_data_function($fn, $ln); //returns 1 or 0 echo out;
references:
Comments
Post a Comment