简体   繁体   中英

echo form with onblur onfocus

I'm trying to echo a form that contains multiple input fields. I want to use onblur and onfocus (see the conditions below in the code), but the javascript function doesn't work when I echo it with php. Any help to rectify the issue\\technical explanations would be appreciated.

echo '<form action="file.php" method="post">
<input type="text" style="width: 450px" maxlength="50" value="' . $data . '" name="data" id="data"
onblur="if (this.value == "") {this.value = "data";}"
onfocus="if (this.value == "data") {this.value = "";}" />
<input type="submit">
</form>';

This is difficult to read:

echo '<form action="file.php" method="post">
<input type="text" style="width: 450px" maxlength="50" value="' . $data . '" name="data" id="data"
onblur="if (this.value == "") {this.value = "data";}"
onfocus="if (this.value == "data") {this.value = "";}" />
<input type="submit">
</form>';

Use the heredoc syntax, like so:

echo <<< FORM
<form action="file.php" method="post">
<input type="text" style="width: 450px" maxlength="50" value="$data" name="data" id="data" onblur="if (this.value == '') {this.value = '$data';}"
onfocus="if (this.value == '$data') {this.value = '';}">
<input type="submit">
</form>
FORM;

Note that I swapped some of the double quotes for single quotes because they were nested.

For the event handlers (onfocus and onblur), the outer quotes are double quotes. These enclose the attribute values. Within the double quotes any strings must be single quoted to avoid closing the attribute value before it has been completed.

http://php.net/manual/en/language.types.string.php#language.types.string.syntax.heredoc

This looks like what you were trying to achieve with the inline js events. if the value is an empty string on blur it will get the [data-default] value, if the value is the [data-default] value on focus it will be cleared.

in php you should set both the [value] and [data-default] values at the same time.

echo '<input type="text" value="'. $data .'" data-default="'. $data . '">';

 var formInput = document.querySelector('#data'); formInput.addEventListener('focus', function( e ){ if( this.value === this.dataset['default'] ){ this.value = ''; } }, false ); formInput.addEventListener('blur', function( e ){ if( this.value === '' ){ this.value = this.dataset['default']; } }, false ); 
 <form action="file.php" method="post"> <input type="text" name="data" id="data" value="something" data-default="something" /> </form> 

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