开发者

onblur deletes data when submit, why?

I have the following script.

<input style="color: #ccc" type="text" value="something" name="country"  
onFocus="if (this.value == 'something') {
    this.value='';this.style.color='black';}" 
onblur="if (this.value != 'something') {
    this.value='something'}" />
<input  type="submit" value="save"  />

On blur, the input value is set to a default value, as it's supposed to. When i click on submit button, the value is also set to "something"; when submitting, i need to post th开发者_运维知识库e data the user wrote in the input, rather than the default.

What can I do if I want that when I click on submit button, the input value doesn't change? thanks


I think this is what you're after

 <input style="color: #ccc" type="text" value="something" name="country"  
onFocus="if (this.value == 'something') {
    this.value='';this.style.color='black';}"
  onblur="if(this.value == ''){this.value = 'something'}" />
<input  type="submit" value="save"  />


I think your onblur function might be a little off. The way you currently have it is replacing any value the user enters. Try this:

onblur="if (this.value == '') {this.value='something'}"

In other words, only put "something" back into the text field if we left it blank.


If you're setting the value of the input to hide what the user wrote, it's simpler to change the input type between a text input and a password input.

<input style="color: #ccc" type="password" name="country"
       onFocus="this.type='text'; this.style.color=''"
       onblur="this.type='password'" />

If you want the input to display the default value when it doesn't have focus, but submit the value the user last typed, you can use a hidden input. Since JS might be disabled/unavailable, you'll either need to change the inputs' names in JS or resolve which input to get the value from server-side.

<input type="hidden" name="country_actual" />
<input style="color: #ccc" type="password"
       onFocus="this.value='';this.style.color='black';" 
       onblur="this.form.elements.counter.value=this.value; this.value='something'" />
<script type="text/javascript">
    document.forms[document.forms.length-1].elements.country.name = '';
    document.forms[document.forms.length-1].elements.country_actual.name = 'country';
</script>

If you want to keep the user typed value only when the focus switches from the input to the submit button, it's difficult to impossible. When focus switches, the blur event may fire before the focus event (depending on the browser), so you can't use that to check the newly focused element, which you could otherwise do with document.activeElement. Furthermore, on webkit based browsers, buttons (whether <input> or <button> elements) don't seem to get focus.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜