Hello.

I have one question.

I have a form which I wish to clear all fields upon refresh/reload (except one field).

Using onload and onunload, all fields are cleared but I need to retain one field upon a User doing this action.

Is there a method where I can perhaps loop through all the fields, choosing those I wish to clear, and the one I want to retain?

Thank you in advance for any assistance or advice.

Matthew

Recommended Answers

All 8 Replies

Member Avatar for diafol

You could add a class to the formfield in question (e.g. "keep") and clear all except that one.

e.g. with jQ:

$("input:not(.keep)").val('');
commented: Thank you. +8

diafol:

I will try your example right now.

Thank you.

I added that code.

The field itself (Not the input value) disappeared and code displayed on the page.

I will have to play with this to try to get it to work.

You will of course need to make sure jquery is included in your page and your code is within script tags etc.

Member Avatar for diafol

OK, example:

<body>

<!--SOME STUFF-->

<input name="somebox" class="keep" value="Keep Me" />
<input name="someotherbox" value="Clear Me" />
<input name="someotherbox2" value="Clear Me Two" />

<!--SOME MORE STUFF MAYBE -->

<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.2/jquery.min.js"></script>
<script>
    $("input:not(.keep)").val('');
</script>
</body>

Not tested. Not worth including jQ just for this though. Perhaps look at native js alternative.

Just jumping here. Have no code to share at the moment but while reading, seems to me these suggestions aren't going to work since the page is being reloaded. The solution requires passing the value from page to page, correct?

Without a page reload the diafols suggestion is very applicable. Or I'm just missing or misreading here?

Member Avatar for diafol

Ah, missed something myself! In order to populate just one field you need to pass that in a cookie or localstorage I would imagine. When you say refresh - do you mean a manual F5 type action or a link / button click on page?

I missed the focus of the question, which was to retain one field. I jumped in with clearing everything except one field.

What I mean by reload is to use the back button or the refresh icon for the given page.

I have multiple fields in a form - Upon reload I wish to clear all fields except for one.

I am easily able to clear all fields by using onload and onUnload but that unfortunately clears all fields.

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.