Tek-Tips is the largest IT community on the Internet today!

Members share and learn making Tek-Tips Forums the best source of peer-reviewed technical information on the Internet!

  • Congratulations Mike Lewis on being selected by the Tek-Tips community for having the most helpful posts in the forums last week. Way to Go!

Newbie question

Status
Not open for further replies.

gpet

Technical User
May 18, 2007
17
GR
hi everyone
I am new in php so forgive me if the question is to easy.

How a textbox that has not a default value can take only two values 0 or 1 everytime that i submit a page.First time one second 0 and so on.

Thanks all in advanced

Sorry if my english are bad
 
textboxes (the textarea element or the <input type="text"> element) are designed for free text input. you can contrain them with javascript but then you are using them outside of their design parameters.

conversely, to provide a boolean switch, html provides you with the checkbox control.

the problem with a checkbox control is that its value is only submitted if it is checked. so your server code needs to check whether the checkbox is actually submitted and assign a value if not.

for this form, for example

Code:
<form method="post" action="$_SERVER['PHP_SELF']">
 <input type="checkbox" name="blnSwitch" /> Click for true<br/>
 <input type="submit" name="submit" value="submit"/>
</form>

you would receive the script as follows

PHP:
if (isset($_POST['submit'])){ //form has been submitted
  $checkbox = isset($_POST['blnSwitch']) ? 1 : 0;
  echo "the checkbox value was $checkbox";
}

alternatively you could use javascript to create an 'advanced checkbox'

Code:
<script>
function advCbox(ctrl){
 var a_ctrl = document.getElementById('adv' + ctrl.name);
 a_ctrl.value = ctrl.checked ? '1' : '0';
}
</script>
<form method="post" action="$_SERVER['PHP_SELF']">
 <input type="checkbox" name="_blnSwitch" onchange='advCbox(this);' /> Click for true<br/>
 <input type="hidden" name="blnSwitch" id="adv_blnSwitch" value="0"/>
 <input type="submit" name="submit" value="submit"/>
</form>

your receiving code would then just use the value of $_POST['blnSwitch']

given that not all users have javascript enabled, my preference would always be for the server side validation solution (the first). If you want to use a full javascript validation solution then this is outside of the scope of this forum and you should take the question to our javascript brethren.
 
Status
Not open for further replies.

Part and Inventory Search

Sponsor

Back
Top