I have two buttons. Both buttons have two attributes – “data-from“ and “data-to“. When any of the button is clicked, these attribute values need to be passed on to a hidden field and the form need to be submitted (POST). Before submitting, I need to alert the attribute values from the hidden fields also. How do I do that?
Note: The following code is written using ASP.NET Webforms.
<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
<title></title>
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.7.1/jquery.min.js" type="text/javascript"> </script>
<script type="text/javascript">
$(document).ready(function ()
{
$('#mainDiv input[type="button"]').on('click', function ()
{
alert('HAi');
$('#from').val($(this).attr('data-from'));
$('#to').val($(this).attr('data-to'));
//alert($('#from').val);
//alert($('#to').val);
$('this').closest('form').submit();
});
});
</script>
</head>
<body>
<div id="mainDiv">
<form id="form1" runat="server">
<div>
<input type="button"
value="Show March Programs"
data-from="01-03-2012"
data-to="31-03-2012" />
<input type="button"
value="Show 2012 Programs"
data-from="01-01-2012"
data-to="31-12-2012" />
<input type="hidden" id="from" value="1" />
<input type="hidden" id="to" value="2" />
</div>
</form>
</div>
</body>
</html>
READING:
Your code is almost there. It was failing on the submit function which you can use either the generic $(‘form’) (in case you have only one form in your page or you can change it to $(‘#form1’). You need to change also the action and method in your form.
Now, I see that you are using non-standard attributes to store values, this ‘works’ but is not syntactically correct. You might need to change it if you want to pass the validation.