MiscellaneousUser MiscellaneousUser - 2 months ago 6
Ajax Question

Beginners to JQuery

The following is my form

<form id="form1">
<table>
<tr><td >Name:</td><td class="CommentsRight"><input type="text" name="txtName" style="width:90%" /></td></tr>
<tr><td >Email: (Optional)</td><td class="CommentsRight"><input type="text" Name="txtEmail" style="width:90%" /></td></tr>
<tr><td >Comment: </td><td class="CommentsRight"><textarea type="text" style="width:90%" Name="txtMessage" TextMode="MultiLine" Rows="10"></textarea></td></tr>
<tr><td ></td><td class="CommentsRight"><input type="submit" width="100" ID="cmdSubmit" onclick="javascript: SubmitComment();" />&nbsp;&nbsp;&nbsp;<input type="button" ID="cmdCancel" Text="Reset" value="Reset" onclick="document.getElementById('form1').reset();" /></td></tr>
</table>
</form>

<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.8.3/jquery.min.js" type="text/javascript"></script>


function SubmitComment()
{
alert($("txtName").val());

$.ajax({
type: "POST",
url: "@(Request.RawUrl)",
data: '{txtCode: "' + $("#txtName.value") + '" }',
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function () { alert('success'); } ,
failure: function (response) {
alert(response.d);
}
});
}


The alert is bringing back undefined all the time for the alert, i'm a beginner to Ajax/Jquery. I've tried #txtName, I've tried input also but it doesn't return any value I put into the txtName, what am I do wrong. I want to then extend data so i pass all the input strings into the data.

In short,


  1. How do I get the value of txtName.text

  2. How do I build up the data string so it contains separated data values



Your help most appreciated.

Answer

You can not use $("txtName") as you did it. jQuery will not know what to select. There is no class/id or any other selector. Rather use $("input[name=txtName]").val() or give the txtName a class or id (like i did in my example below).

If you want to send the form now in a nice Json you need to serialize it:

var data = $("#form1").serialize();

https://jsfiddle.net/gahapv4t/

Comments