mardi 14 avril 2015

How to submit a form using JQuery depending on which option a user chooses

I've looked around at a few different questions with regards to this topic and no breakthroughts. What I'm trying to do is when the user clicks on the submit button I show 3 buttons on the screen and if the user clicks the third button the form submits. Otherwise I prevent the form from submitting.


However I'm having trouble implementing this. Currently I'm doing it this way and from my research i saw the very obvious mistake I was making with calling e.preventDefault() as soon as the form is submitted which prevents it from being able to be submit.


Hopefully in my code you will see what I'm trying to do. Show the three options before the form is submit and only submit if the third option is selected.


HTML:



<form action="some_url" method="post">
<input type="text" value="" id="fname" />
<input type="submit" value="Submit" />
</form>
<br/>
<div id="option-box">
<span id="option-a">Option A</span>
<span id="option-b">Option B</span>
<span id="option-c">Option C</span>
</div>


JQuery:





$('form').submit(function (e) {
e.preventDefault();
$('#option-box').show();

$('#option-a').click(function () {
alert('option a');
//Do something else
});
$('#option-b').click(function () {
alert('option b');
//Do something else
});
$('#option-c').click(function () {
alert('option c - SUBMIT');
$('form').submit();
});

});



#option-box {
display: none;
}
#option-box span {
background:green;
color: white;
display: block;
cursor: pointer;
padding:5px;
margin: 10px 0;
text-align:center;
max-width: 100px;
}



<script src="http://ift.tt/1g1yFpr"></script>
<form action="some_url" method="post">
<input type="text" value="" id="fname" />
<input type="submit" value="Submit" />
</form>
<br/>
<div id="option-box">
<span id="option-a">Option A</span>
<span id="option-b">Option B</span>
<span id="option-c">Option C</span>
</div>



Here is a fiddle of my current code:


http://ift.tt/1ar769D


Aucun commentaire:

Enregistrer un commentaire