Вопрос

I have two forms in a JSP page, one contains a text field. I need to make sure that whenever the other form is submitted, it copies the value contained in that text field, and writes it's text value in an hidden parameter.

More clearly:

  1. One form is named "search";
  2. Another form is named "changeInitialForm";
  3. The text field is contained in the "search" form, and it's name is "searchString";
  4. The "changeInitialForm" has an hidden field, also this named "searchString";
  5. The purpose is to make sure that whether the user submits one or another form, a "searchString" parameter is passed, with the value of the text field.

I tried to include an action in javascript, executed when the "changeInitialForm" is submitted, that reads the text field value and writes it into the hidden parameter:

function searchContacts(form)
{
    var searchString= document.search.searchString.value;
    form.searchString.value= searchString;
}

...

<form name="search" >
    <input type="text" name="searchString">
    <button name="search"> Cerca </button>
</form>

...


<form name="changeInitialForm" method="post" action="AddressBookView.jsp" onSubmit="searchContacts(this.form);">
    <input type="hidden" name="selectedInitial"/>
    <input type="hidden" name="status" value="view"/> 
    <input type="hidden" name="searchString" />
</form>   

But after the "changeInitialForm" is submitted, regardless of the text field value, and empty parameter is passed, I am seeing this with firebug:

enter image description here

I would also appreciate an alternative solution, because I know what I am doing is tricky, but I don't find another method to do that. "search" and "changeInitialForm" cannot be joined in a single form, because they do very different things.

Это было полезно?

Решение

The following seems to work

function searchContacts(form)
{
    var searchString= document.search.searchString.value;
    form.searchString.value= searchString;
}

...

    Form 1:
<form name="search" >
    <input type="text" name="searchString">
    <button name="search"> Cerca </button>
</form>

...

    Form 2:
<form name="changeInitialForm" method="post" action="AddressBookView.jsp" onSubmit="searchContacts(this);">
    <input type="hidden" name="selectedInitial"/>
    <input type="hidden" name="status" value="view"/> 
    <input type="hidden" name="searchString" />
</form>

Notice that searchContacts(this.form) was replaced with searchContacts(this).

UPDATE after some precisions by the author of the question:

The onsubmit event is not triggered when form.submit() is called by some javascript code. Thus, what you need when you submit the form is to call searchContacts separately, for example using

searchContacts(document.changeInitialForm);
document.changeInitialForm.submit();
Лицензировано под: CC-BY-SA с атрибуция
Не связан с StackOverflow
scroll top