All,
Is this the best way to get the value of a currently-checked/unchecked checkbox?
The number of checkboxes is arbitrary so I need a way to get the value of the checkbox that was checked or unchecked.
By looking at Firebug, I see that by using:
this.defaultValue
I can get the value of the currently-checked/unchecked checkbox but not sure if that's really the best way.
Here is the HTML and below is the Javascript click handler
<div id="ClubSponsorshipPartial">
<table class="table-grid">
<tr>
<td>
<input type="checkbox" value="000000244187" id="slpBackgroundCheck" name="slpBackgroundCheck"> Person #1
<input type="checkbox" value="000000533796" id="slpBackgroundCheck" name="slpBackgroundCheck"> Person #2
<input type="checkbox" value="000000533796" id="slpBackgroundCheck" name="slpBackgroundCheck"> Person #3
</td>
</tr>
</table>
</div>
<script type="text/javascript">
$(document).ready(function () {
$("#ClubSponsorshipPartial input[type=checkbox]").click(function (e) {
var queryStr = '';
var clubKeyNumber = '';
var receivedBackgroundCheckChecked = false;
var memberId = this.defaultValue
clubKeyNumber = 'K06253';
receivedBackgroundCheckChecked = ($("#ClubSponsorshipPartial input[type=checkbox]").is(":checked") ? "true" : "false");
queryStr = "memberId=" + memberId + "&isChecked=" + receivedBackgroundCheckChecked;
$.ajax({
type: "POST",
url: '/Dashboard/BackgroundCheck',
data: queryStr,
datatype: 'json',
success: function (data) {
$.notification({
content: 'SLP Advisor Background Check status saved.',
error: false,
timeout: 5000
});
},
failure: function (data) {
$.notification({
content: 'Error saving SLP Advisor Background Check status.',
error: true,
timeout: 5000
});
},
timeout: 5000
});
});
});
</script>
the id should be unique in your page document, and you should use $(this) to mapping current DOM, you can try below code, may help;
http://jsfiddle.net/kJQr9/
Related
In the console,I am getting name based on id.How to bind that name into the html page.
Here is my code..
function getEventname(){
var clid=$('#eventid').val();
console.log("i am ok" + clid);
$.ajax({
type: "GET",
url: "EduManage.jsp",
data: {
control:'ajax',
ch:'1',
key:'1_0a1m_1',
eventid:clid
},
success: function(data) {
console.log("i am ok" + data);
(what to do to bind the name in the html page)
}
});
}
Now the HTML is;
<td class="bg1">
Event Id :
</td>
<td class="bg1" width="25%">
<input name="eventid" type="text" id="eventid" size="10" maxlength="10" onblur="getEventname()"/>
</td>
<td class="bg1" width="40%">
Event Name :
</td>
<td class="bg1" width="25%">
<input type="text" name="eventname" id="eventname">
</td>
In the console,I am getting name as i am ok seminar .How to bind that name in the HTML page automatically when id is given.
Can anyone help?
So your Javascript function should be;
function getEventname(){
var clid=$('#eventid').val();
console.log("i am ok"+clid);
$.ajax({
type: "GET",
url: "EduManage.jsp",
data: {
control:'ajax',
ch:'1',
key:'1_0a1m_1',
eventid:clid
},
success: function(data) {
console.log("i am ok"+data);
//The one line change
$("#eventname").val(data);
}
});
}
So you had already implemented everything. All you need to do is add data in some element. If you want to add it in td then use this:
$.ajax({type: "GET",url: "EduManage.jsp",data: {control:'ajax', ch:'1', key:'1_0a1m_1', eventid:clid},
success: function(data) {
console.log("i am ok"+data);
$("td.last").append(data);
(what to do to bind the name in the hmtl page)
}
});
and add a new html tag:
<td class="last"></td>
You can also update the html using jquery but its not a practice to do so.
Hope this works.
This is hpw i'm filing my dropdown box
$.ajax({
url: "CheckinRelatedMember",
type: "POST",
data: { ClubId: localStorage.getItem("ClubId"), memacctno: localStorage.getItem("memacctno") },
async: false,
success: function (data) {
var RelatedMembers;
RelatedMembers = JSON.parse(data.CheckinRelatedMemberResult);
self.RelMembers(RelatedMembers);
How to get Option value from knockout dropdown list. I had successfully binded an dropdown box. but my problem is while i retrieve value from tag. option value unable to appear.
function FillCheckInRec() {
submemacctno = document.getElementById("RelateMem")[0].value;
i need to pass selected option value to FillCheckInRec() method.
<p>
<label>
Select Member
</label>
<select id="RelateMem" class="input-medium" data-bind="options: RelMembers, optionsText:'Name',optionvalue:'AcctNo', value: 'AcctNo'"></select>
</p>
But while i pass select value into FillCheckinRec() method, value comes like this (""). how to get AcctNo From dropdown list. Please Help Me!
Try something like this
view:
<p>
<label>Select Member</label>
<select data-bind="options: RelMembers, optionsText:'Name',optionsValue:'AccNo', value:AcctNo"></select>
</p>
<hr/>
<b><label data-bind="text:AcctNo"></label></b>
viewModel:
var ViewModel = function () {
var self = this;
self.RelMembers = ko.observableArray();
self.AcctNo = ko.observable();
$.ajax({
url: '/echo/json/',
type: "POST",
data: {},
success: function (data) {
var RelatedMembers = [{
'Name': 'One',
'AccNo': 1
}, {
'Name': 'Two',
'AccNo': 2
}, {
'Name': 'Three',
'AccNo': 3
}]
self.RelMembers(RelatedMembers);
}
});
};
ko.applyBindings(new ViewModel());
working sample here
Well I got fix this issue, Here is my code.
var submemacctno = $("#RelateMem").val();
<select id="RelateMem" class="input-medium" data-bind="options: RelMembers, optionsText:'Name',optionsValue:'AcctNo', value:'AcctNo'"></select>
This is my HTML Code, Rest of everything are same.
Thank You!
I have a simple ASP MVC3 #Html.TextBox that I'm using to input search criteria. However, I need to append the value to the URL in an Ajax call as a query string. How would I go about this? Below is the HTML in the view:
<div class="editor-field">
#Html.TextBox("searchString")
<span onclick='GetCompName(searchString);'>
<input type="image" src="#Url.Content("~/Content/Images/Filter.bmp")" alt="Filter" />
</span>
</div>
And here is the Ajax
function GetCompName(searchString) {
var request = $.ajax({
type: 'POST',
url: 'http://quahildy01/OrganizationData.svc/AccountSet?$select=AccountId,Name,neu_UniqueId&$filter=startswith(Name,' + searchString + ')',
dataType: 'html',
success: function (data) {
alert(data);
},
error: function (data) {
alert("Unable to process your resquest at this time.");
}
});
}
I will also want to output the returned value into another text box. If anyone knows how to do that that would be really helpful as well. Thanks!
the basic problem with your code is the searchString in onclick='GetCompName(searchString); always gonna be literally "serchString", you must specified the parameter in base the value in the input, like this $('.searchbox').val()
keep your javascript unobstructive.
HTML code
<div class="editor-field">
#Html.TextBox("searchString", null, new { #class = "serachbox" })
<span class="searchbox-trigger">
<input type="image" src="#Url.Content("~/Content/Images/Filter.bmp")" alt="Filter" />
</span>
</div>
Set de handler for the event span click
$(document).ready(function() {
$('.searchbox-trigger').click(GetProgramDetails);
});
and your ajax request
function GetProgramDetails() {
var request = $.ajax({
type: 'POST',
url: 'http://quahildy01/OrganizationData.svc/AccountSet?$select=AccountId,Name,neu_UniqueId&$filter=startswith(Name,' + $('.searchbox').val() + ')',
dataType: 'html',
success: function (data) {
alert(data);
},
error: function (data) {
alert("Unable to process your resquest at this time.");
}
});
}
How to pass Id from javascript to Controller action in mvc3 on ajax unobtrusive form submit
My script
<script type="text/javascript">
$(document).ready(function () {
$("#tblclick td[id]").each(function (i, elem) {
$(elem).click(function (e) {
var ID = this.id;
alert(ID);
// var url = '#Url.Action("Listpage2", "Home")';
var data = { Id: ID };
// $.post(url,data, function (result) {
// });
e.preventDefault();
$('form#myAjaxForm').submit();
});
});
});
</script>
the how to pass Id on using $('form#myAjaxForm').submit(); to controller
instead of
$.post(url,data, function (result) {
// });
My View
#using (Ajax.BeginForm("Listpage2", "", new AjaxOptions
{
UpdateTargetId = "showpage"
}, new { #id = "myAjaxForm" }))
{
<table id="tblclick">
#for (int i = 0; i < Model.names.Count; i++)
{
<tr>
<td id='#Model.names[i].Id'>
#Html.LabelFor(model => model.names[i].Name, Model.names[i].Name, new { #id = Model.names[i].Id })
<br />
</td>
</tr>
}
</table>
}
</td>
<td id="showpage">
</td>
I would avoid using the Ajax Beginform helper method and do some pure handwritten and Clean javascript like this
<table id="tblclick">
#foreach(var name in Model.names)
{
<tr>
<td id="#name.Id">
#Html.ActionLink(name.Name,"listpage","yourControllerName",
new { #id = name.Id },new { #class="ajaxShow"})
</td>
</tr>
}
</table>
<script>
$(function(){
$(".ajaxShow")click(function(e){
e.preventDefault();
$("#showpage").load($(this).attr("href"));
});
});
</script>
This will generate the markup of anchor tag in your for each loop like this.
<a href="/yourControllerName/listpage/12" class="ajaxShow" >John</a>
<a href="/yourControllerName/listpage/35" class="ajaxShow" >Mark</a>
And when user clicks on the link, it uses jQuery load function to load the response from thae listpage action method to the div with id showPage.
Assuming your listpage action method accepts an id parameter and returns something
I am not sure for $.post but I know window.location works great for me.
Use this instead and hopefully you have good results :)
window.location = "#(Url.Action("Listpage2", "Home"))" + "Id=" + ID;
replace $('form#myAjaxForm').submit(); with this code and nothing looks blatantly wrong with your jscript.
Just use a text box helper with html attribute ID.
#Html.TextBox("ID")
You can do this too:
var form = $('form#myAjaxForm');
$.ajax({
type: "post",
async: false,
url: form.attr("action"),
data: form.serialize(),
success: function (data) {
// do something if successful
}
});
I have to execute a authentication process using JQuery. I have two textbox UserName and Password and two button are Login and Submit.
If i am clicking on Submit button then it will automatically fire validation that good and this functionality i have to implement on Login button click.
So how could i achieve automatic validation on button click?
Why i would like this:
Usin JQuery it is sending a request to the server with UserName and
Password during that time i will display Processing....
Then it will verify supplied value with database and return response
with Success or Failed then i will display either Success or Failed.
Here is the code snippet:
<script src="#Url.Content("~/Scripts/jquery.validate.min.js")" type="text/javascript"></script>
<script src="#Url.Content("~/Scripts/jquery.validate.unobtrusive.min.js")" type="text/javascript"></script>
#Html.ValidationSummary(true, "Login was unsuccessful. Please correct the errors and try again.")
#using (Html.BeginForm(null, null, FormMethod.Get, new { id = "Form1", name = "Form1" }))
{
<table>
<tr>
<td>
User Name
</td>
<td>#Html.TextBoxFor(u => u.UserName, new { id = "txtUser" }) #Html.ValidationMessageFor(u => u.UserName)
</td>
</tr>
<tr>
<td>
Password
</td>
<td>#Html.TextBoxFor(u => u.Password, new { id = "txtPassword" }) #Html.ValidationMessageFor(u => u.Password)
</td>
</tr>
<tr>
<td>
</td>
<td>
<input type="button" value="Login" onclick="checkAuthentication();" />
<input type="submit" value="Submit" />
</td>
</tr>
<tr>
<td colspan="2">
<div id="dvStatus" class="loginMessageStatus">
</div>
</td>
</tr>
</table>
}
<script language="javascript" type="text/javascript">
function getUserCredentials() {
var user = jQuery('#txtUserName').val();
var pass = jQuery('#txtPassword').val();
return { UserName: user, Password: pass };
}
function clearUserCredentials() {
jQuery('#txtUserName').val("");
jQuery('#txtPassword').val("");
jQuery('#txtUserName').focus();
}
function checkAuthentication() {
jQuery('#dvStatus').html("<div class='requestProcess'></div><div class='requestMessage'>Please wait...</div>")
var postData = getUserCredentials();
var ajaxResponse = $.ajax({
type: "post",
url: '#Url.Action("Index", "Login")',
dataType: 'json',
contentType: "application/json; charset=utf-8",
data: JSON.stringify(postData),
success: function (result) {
var res = jQuery.parseJSON(result);
if (res.Success == true) {
jQuery('#dvStatus').html("<div class='requestSuccess'></div><div class='requestMessage'>Your are successfully logged in. Redirecting...</div>")
jQuery.doTimeout(100, redirectToPage);
}
else {
jQuery('#dvStatus').html("<div class='requestFailed'></div><div class='requestMessage'>Error: " + res.Message + ". <a href='javascript:void(0)' onclick='clearUserCredentials()'>Try Again</a></div>")
}
}
});
}
function redirectToPage() {
href = '#Url.Action("Index", "TabMaster")';
window.location.href = href;
}
Note:-
Validation completely work with Submit button
Verifying process completely work with Login button ( just i have to integrate validation with Login button)
you can do the validation using the onclick of the submit button with the following event handler:
Add an identifier to the button:
<input id="SubmitButton" type="submit" value="Submit" />
JavaScript:
$(document).ready(function(){
$("#SubmitButton").click(function(){
return checkAuthentication();
});
});
Change the Validation method to return whether it failed or not:
function checkAuthentication() {
var _user = jQuery.trim(jQuery('#txtUserName').val());
var _pass = jQuery.trim(jQuery('#txtPassword').val());
if (_user.length == 0 || _pass.length == 0) {
jQuery('#dvStatus').html("<div class='requestFailed'></div><div class='requestMessage'>User Name and Password are required!</div>")
return false;
}
else {
jQuery('#dvStatus').html("<div class='requestProcess'></div><div class='requestMessage'>Please wait...</div>")
var postData = getUserCredentials();
var ajaxResponse = $.ajax({
type: "post",
url: '#Url.Action("Index", "Login")',
dataType: 'json',
contentType: "application/json; charset=utf-8",
data: JSON.stringify(postData),
success: function (result) {
var res = jQuery.parseJSON(result);
if (res.Success == true) {
jQuery('#dvStatus').html("<div class='requestSuccess'></div><div class='requestMessage'>Your are successfully logged in. Redirecting...</div>")
jQuery.doTimeout(100, redirectToPage);
}
else {
jQuery('#dvStatus').html("<div class='requestFailed'></div><div class='requestMessage'>Error: " + res.Message + ". <a href='javascript:void(0)' onclick='clearUserCredentials()'>Try Again</a></div>")
}
}
});
return true;
}
}
This should then stop the submit if the validation fails.
I have solved this one:
I have used only submit button
<input id="btnLogin" type="submit" value="Login" />
Following are the updated code
<script language="javascript" type="text/javascript">
$(document).ready(function () {
//$.preloadCssImages();
$("#btnLogin").click(function () {
if ($("#Form1").valid() == true) {
checkAuthentication();
return false;
}
});
});
function getUserCredentials() {
var user = jQuery('#txtUserName').val();
var pass = jQuery('#txtPassword').val();
return { UserName: user, Password: pass };
}
function clearUserCredentials() {
jQuery('#txtUserName').val("");
jQuery('#txtPassword').val("");
jQuery('#txtUserName').focus();
}
function checkAuthentication() {
jQuery('#dvStatus').html("<div class='requestProcess'></div><div class='requestMessage'>Please wait...</div>")
var postData = getUserCredentials();
var ajaxResponse = $.ajax({
type: "post",
url: '#Url.Action("Index", "Login")',
dataType: 'json',
contentType: "application/json; charset=utf-8",
data: JSON.stringify(postData),
success: function (result) {
var res = jQuery.parseJSON(result);
if (res.Success == true) {
jQuery('#dvStatus').html("<div class='requestSuccess'></div><div class='requestMessage'>Your are successfully logged in. Redirecting...</div>")
jQuery.doTimeout(100, redirectToPage);
}
else {
jQuery('#dvStatus').html("<div class='requestFailed'></div><div class='requestMessage'>Error: " + res.Message + ". <a href='javascript:void(0)' onclick='clearUserCredentials()'>Try Again</a></div>")
}
}
});
}
function redirectToPage() {
href = '#Url.Action("Index", "TabMaster")';
window.location.href = href;
}
</script>