- How to submit the form using javascript with «this»
- 7 Answers 7
- Related
- Hot Network Questions
- Subscribe to RSS
- How can I submit a POST form using the tag?
- Как отправить форму по нажатию на ссылку?
- Submit form using tag
- 10 Answers 10
- How to submit a form with JavaScript by clicking a link?
- 9 Answers 9
- The best way
- The best JS way
- The easy, not recommandable way (the former answer)
- All ways
How to submit the form using javascript with «this»
Why do you want to do this ? It is a good practice to put your code in separate javascript file. Is there any reason you could not separate the markup from the script ?
7 Answers 7
Submit form using this.form.submit()
i.e in your case it will be like
But it highly recommended to use form name
otherwise if you are comfortable using jquery you can also use jquery closest function
Actually it seems to work when is replaced with the form’s id also.
Althoughy I would strongly recommend you research the practice known as Unobtrusive Javascript
I use this solution for unknown form name:
function submitForm(originator) < var pN=originator.parentNode; while (true) < if (pN&&pN.nodeName=='FORM') < pN.submit(); break; >pN=pN.parentNode; > >
and now on any document’s object event we can use this function:
Say you have n number of forms on your page. You can submit i+1 th form by using:
So if you have just one, and want to submit on link click,
should be your onclick attribute’s value
but then i need to diff code for every href. I have around 30 files and i am replacing the submit button with href with shell script
I use more tricky way. make your button looks like
Related
Hot Network Questions
Subscribe to RSS
To subscribe to this RSS feed, copy and paste this URL into your RSS reader.
Site design / logo © 2023 Stack Exchange Inc; user contributions licensed under CC BY-SA . rev 2023.7.27.43548
By clicking “Accept all cookies”, you agree Stack Exchange can store cookies on your device and disclose information in accordance with our Cookie Policy.
How can I submit a POST form using the tag?
All well and good, but you’ve still chosen to answer a different question than was asked. And given that erasable ink is, in fact, a viable product produced on an industrial scale.
FWIW, I sympathize with your answer and it’s what I personally would rather see in web apps I have to maintain. I’m just explaining the downvote — which I didn’t leave, by the way. 😉
You need to use javascript for this.
You have to use Javascript submit function on your form object. Take a look in other functions.
In case you use MVC to accomplish it — you will have to do something like this
I just went through some examples here and did not see the MVC one figured it won’t hurt to post it.
Then on your Action in the Controller I would just put On the top of it. I believe if you don’t have on the top of it it would still work but explicitly putting it there feels a bit safer.
Unfortunately, the obvious way of just styling the button in CSS as an anchor tag, is not cross-browser compatible, since different browsers treat
The above example will be showing ‘Two’ and transmit ‘parameter:One’ in FireFox, while it will show ‘One’ and transmit also ‘parameter:One’ in IE8.
The way around is to use hidden input field(s) for delivering data and the button just for submitting it.
Note, that this method has a side effect that besides ‘parameter:blaah’ it will also deliver ‘delete:Delete’ as surplus parameters in POST.
You want to keep for a button the value attribute and button label between tags both the same (‘Delete’ on this case), since (as stated above) some browsers will display one and some display another as a button label.
Как отправить форму по нажатию на ссылку?
Этот вопрос входит, наверное, в ТОП10 вопросов на форумах 🙂 Скорей всего это требование дизайнера или заказчика.
Итак, решение, на первый взгляд, простое:
Но тут же возникает (как ни странно 🙂 следующий вопрос это, а если JS будет у посетителя отключен?
Изменим наш код на:
addEvent ( window , ‘load’ , windowLoad ) ;
/* Кроссбраузерное добавление обработчика события */
function addEvent ( obj , evType , fn ) <
if ( obj. addEventListener ) <
obj. addEventListener ( evType , fn , false ) ;
> else if ( obj. attachEvent ) <
obj. attachEvent ( ‘on’ + evType , fn ) ;
>
>
/* Получаем родительскую форму для элемента */
function getParentForm ( obj ) <
while ( ( obj = obj. parentNode ) ) <
if ( obj. nodeName == ‘FORM’ ) <
break ;
>
>
return obj ;
>
/* Ищем все submit-кнопки с классом link и заменяем их на ссылки */
function windowLoad ( ) <
var buttons = document. getElementsByTagName ( ‘input’ ) ;
for ( var i = 0 ; i < buttons. length ; i ++ ) <
if ( buttons [ i ] . getAttribute ( ‘type’ ) == ‘submit’ && buttons [ i ] . className == ‘link’ ) <
var link = document. createElement ( ‘a’ ) ;
link. appendChild ( document. createTextNode ( buttons [ i ] . getAttribute ( ‘value’ ) ) ) ;
link. setAttribute ( ‘href’ , ‘#’ ) ;
addEvent ( link , ‘click’ , linkClick ) ;
var parent = buttons [ i ] . parentNode ;
parent. removeChild ( buttons [ i ] ) ;
parent. appendChild ( link ) ;
>
>
>
/* Отправляем форму по нажатию на ссылку */
function linkClick ( e ) <
var e = window. event || e ;
var target = e. target || e. srcElement ;
var parentForm = getParentForm ( target ) ;
parentForm. submit ( ) ;
Теперь, если JS будет отключен, посетитель увидит вместо ссылки кнопку и все равно сможет отправить форму. Но мы на этом не остановимся. Заставим кнопку выглядеть как ссылка даже если отключен JS. Для того чтобы стилизировать кнопку изменим тег на button , а span нужен для того чтобы можно было в Firefox добавить подчеркивание текста.
Также изменим соответственно часть JS.
var buttons = document. getElementsByTagName ( ‘button’ ) ;
for ( var i = 0 ; i < buttons. length ; i ++ ) <
if ( buttons [ i ] . getAttribute ( ‘type’ ) == ‘submit’ && buttons [ i ] . className == ‘link’ ) <
var link = document. createElement ( ‘a’ ) ;
link. appendChild ( document. createTextNode ( buttons [ i ] . firstChild . firstChild . nodeValue ) ) ;
CSS будет выглядеть следующим образом:
button .link <
/* Первые два свойства нужны чтобы убрать отступы в IE */
overflow : visible ;
width : auto ;
/* Убираем отступы */
margin : 0 ;
padding : 0 ;
/* Убираем все элементы оформления кнопки */
background : none ;
border : none ;
/* Обычный для ссылок курсор */
cursor : pointer ;
>
/* Ссылка обычно подчеркнута */
button .link span <
color : #00f ;
text-decoration : underline ;
>
Для Firefox можно еще добавить -moz-user-select: text; чтобы текст кнопки можно было выделять, но я сомневаюсь в такой надобности.
Остальные стили будут уже зависеть от конкретного дизайна.
- К кнопке не удастся применить псевдоклассы active, visited, а для IE6 и hover
- В IE6 не будут нормально работать несколько button для одной формы
- Без JS можно обойтись. Все зависит от того, насколько вам важна естественность ссылки
UPD
insa предложил еще один очень хороший вариант, единственный минус которого в том, что label не сможет получить фокус.
UPD2
К сожалению, вариант, предложенный insa, не кроссбраузерный (читайте комментарии).
Рабочий пример можно посмотреть здесь.
Submit form using tag
I am trying to submit a form through onclick event on tag. I have tried triggering document.myform.submit(), this.form.submit(), parentNode.submit() etc. but none of this is working! Using a submit button, the code works fine. But I want to use tag in place of that. Need some help.