Javascript href this form

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

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. 😉

Читайте также:  Javascript page refresh disabled

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 ) ;

Читайте также:  Python for ios ipa

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; чтобы текст кнопки можно было выделять, но я сомневаюсь в такой надобности.

Остальные стили будут уже зависеть от конкретного дизайна.

  1. К кнопке не удастся применить псевдоклассы active, visited, а для IE6 и hover
  2. В IE6 не будут нормально работать несколько button для одной формы
  3. Без 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.

 
"/> "/> "/>

)">Serial : else < echo $data_array_ques[$j]['ques_position']; >?>

Serial :

)">
Save Changes | &module=">Delete This Question

Hold on a minute. I’m seeing PHP output $j a lot and it looks like an iterator. is this entire thing occurring in a loop? Are you outputting multiple copies of this form? If so that would mean there are multiple forms with the same ID and name, you’d need to add $j to ID and name like you do with everything else. If not, please disregard.

10 Answers 10

you can do it like this with raw javascript

   
" onclick="document.getElementById('my_form').submit();">submit

For those asking why I have a href element in my anchor tag, its because it’s a compulsory part of an anchor tag, it may well work without but it’s not to spec. So if you want to guarantee rendering etc you must give the engine a fully formed tag. So the above achieves this. You will see href=»#» used sometimes but this is not always wanted as the browser will change the page position.

Источник

How to submit a form with JavaScript by clicking a link?

I use this to integrate a completely hidden form into a page. But there are line breaks before and after the link. Do they come from the form element? And I would like to open the link in a new tab/page, target=»_blank» does not seem to work.

9 Answers 9

The best way

The best way is to insert an appropriate input tag:

The best JS way

var form = document.getElementById("form-id"); document.getElementById("your-id").addEventListener("click", function () < form.submit(); >); 

Enclose the latter JavaScript code by an DOMContentLoaded event (choose only load for backward compatiblity) if you haven’t already done so:

window.addEventListener("DOMContentLoaded", function () < var form = document. // copy the last code block! >); 

The easy, not recommandable way (the former answer)

Add an onclick attribute to the link and an id to the form:

All ways

Whatever way you choose, you have call formObject.submit() eventually (where formObject is the DOM object of the tag).

You also have to bind such an event handler, which calls formObject.submit() , so it gets called when the user clicked a specific link or button. There are two ways:

    Recommended: Bind an event listener to the DOM object.

// 1. Acquire a reference to our . // This can also be done by setting : // var form = document.forms.blub; var form = document.getElementById("form-id"); // 2. Get a reference to our preferred element (link/button, see below) and // add an event listener for the "click" event. document.getElementById("your-id").addEventListener("click", function () < form.submit(); >); 

Now, we come to the point at which you have to decide for the UI element which triggers the submit() call.

Apply the aforementioned techniques in order to add an event listener.

Источник

Оцените статью