I have a textbox in my view page. when i click on imageIcon,it will take data from db and return in alert successfully. But, when i try to bind this response data to textbox, it is not binded correctly. My code in view page is as following :
#foreach (var dateitem in list)
{
<td id="HoursTxt">
#Html.TextAreaFor(modelitem => dateitem.Hours, new { id = string.Format("txtHours"), style = "width:50%;height:70%;" })
#Html.Hidden("CuDate", dateitem.Date)
<img src="~/Images/comment.png" class="prevtest" />
<div style="border:solid;display:none;">
<input type="text" id="TxtNotess" />
<input type="button" id="BtnComment" value="Save" />
</div>
</td>
}
In my onclick event of imageIcon jquery is following:
$('.prevtest').on('click', function () {
var Cudate = $(this).prev('#CuDate').val();
var ProjId = parseInt($(this).parents('tr').find('input[type="hidden"]').val());
var TskId =parseInt($(this).parents('tr').find('td').find('#testTaskId').val());
$.ajax({
type: "POST",
url: "/Timesheet/GetComments?ProjectId=" + ProjId + "&TaskId= " + TskId + "&date= " + Cudate,
success : function(data)
{
alert(data);
$('#TxtNotess').val(data);
alert('success');
},
error:function()
{
alert('Error');
}
});
$(this).next().toggle();
});
the text box with id TxtNotess not bind with response value
Can anyone help me to do this..
Thanks in advance..
First: ID of an element must be unique so use class for the textfield TxtNotess.
<input type="text" class="TxtNotess" />
Then, in the success handler find the textfild with class TxtNotess inside the next sibling of the clicked element
$('.prevtest').on('click', function () {
var Cudate = $(this).prev('#CuDate').val();
var ProjId = parseInt($(this).parents('tr').find('input[type="hidden"]').val());
var TskId = parseInt($(this).parents('tr').find('td').find('#testTaskId').val());
$.ajax({
type: "POST",
url: "/Timesheet/GetComments?ProjectId=" + ProjId + "&TaskId= " + TskId + "&date= " + Cudate,
context: this,//pass a custom context to the ajax handlers - here the clicked element reference
success: function (data) {
alert(data);
$(this).next().find('.TxtNotess').val(data);//find the target textfield
alert('success');
},
error: function () {
alert('Error');
}
});
$(this).next().toggle();
});
$('.prevtest').on('click', function () {
var Cudate = $(this).prev('#CuDate').val();
var ProjId = parseInt($(this).parents('tr').find('input[type="hidden"]').val());
var TskId = parseInt($(this).parents('tr').find('td').find('#testTaskId').val());
$.ajax({
type: "POST",
url: "/Timesheet/GetComments?ProjectId=" + ProjId + "&TaskId= " + TskId + "&date= " + Cudate,
context: this,//pass a custom context to the ajax handlers - here the clicked element reference
success: function (data) {
alert(data);
$('.TxtNotess').val(data);//find the target textfield
alert('success');
},
error: function () {
alert('Error');
}
});
$(this).next().toggle();
});
I gets resolved by using class name for textbox..
Related
How to set jQuery AJAX outside .each on my script below?
$('#btnUpdate').click(function()
{
$('#result').html('');
$('.moduleIDInput').each(function()
{
var uid = $(this).attr('id');
var moduleID = $(this).val();
var chk = new Array();
$('#result').append('<h3>' +$(this).val() + '</h3>');
$('input[data-uid=' + uid + ']:checked').each(function()
{
chk.push($(this).val());
$('#result').append('<div>'+ $(this).val() + '</div>');
});
});
$.ajax(
{
url: "updateGroupAccess.php",
type: "POST",
data:
{
moduleID: moduleID,
chk: chk
},
dataType: "JSON",
success: function (jsonStr)
{
$("#btnUpdate").attr({disabled: true, value: "Update"}).addClass('btn_inact').removeClass('btn_act');;
}
});
});
If I put the AJAX function inside .each function it will submit more than 1.
But I need to put it outside, and found problem moduleID and chk not found.
Scope problem. Define uid and moduleID outside the click.
var uid="";
var moduleID="";
$('#btnUpdate').click(function()
{
$('#result').html('');
$('.moduleIDInput').each(function()
{
uid = $(this).attr('id'); // Assign value for uid
moduleID = $(this).val();
Define the variables in the global scope:
make a function called sendAjax and call it on button click.
In the mean time all your data will be stored in the data global variable (object).
var data={};
$('#btnUpdate').click(function()
{
$('#result').html('');
$('.moduleIDInput').each(function()
{
var uid = $(this).attr('id');
data.moduleID = $(this).val();
$('#result').append('<h3>' +$(this).val() + '</h3>');
$('input[data-uid=' + uid + ']:checked').each(function()
{
data.chk.push($(this).val());
$('#result').append('<div>'+ $(this).val() + '</div>');
});
});
sendAjax();
});
function sendAjax()
{
$.ajax(
{
url: "updateGroupAccess.php",
type: "POST",
data:
{
moduleID: data.moduleID,
chk: data.chk
},
dataType: "JSON",
success: function (jsonStr)
{
$("#btnUpdate").attr({disabled: true, value: "Update"}).addClass('btn_inact').removeClass('btn_act');;
}
});
}
I am working on MVC application that uses API and i want to call a method from the API so that it will load the data to the combo-box. I have no idea on how i can tackle this as am new this.
Thanks.
ClaimController function from the API which got this function.
[RoutePrefix("api/Claim")]
[Route("GetScheme")]
[HttpGet]
public HttpResponseMessage GetScheme()
{
try
{
using (IBusinessLogic logic = new BusinessLogic.Implementation.BusinessLogic())
{
Request.Headers.Clear();
var tmpresults = logic.GetScheme();
var results = (from x in tmpresults.Result select new { text = x.Description, value = x.Id }).ToArray();
var response = Newtonsoft.Json.JsonConvert.SerializeObject(results);
return Request.CreateResponse(HttpStatusCode.OK, results);
}
}
catch (Exception ex)
{
return Request.CreateResponse(HttpStatusCode.BadRequest, ex);
}
}
Views from the Client which is the UI
I want to call that function from API to load the data into the combo-box
function GetAllScheme() {
var select = $("#ddlScheme");
$.ajax({
type: "GET",
url: "http://localhost:55393/_Api/Claim",
dataType: "json",
success: function (data) {
debugger;
var datavalue = data;
var serverResponse = datavalue;
contentType: "application/json";
$.each(serverResponse, function (i, serverResponse)
{
select.append("<option value='" + serverResponse.Description + "'>" + serverResponse.Description + "</option>")
});
},
error: function (xhr) {
alert(xhr.responseText);
}
});
}
Dropdown
<select class="dropdown form-control input-xs required" id="ddlScheme" onclick="GetAllScheme()(this)">
<select
</select>
</div>
You have to append option elements into your select (dropdown) element after you get the server response. Something like this:
function GetAllScheme() {
// get the dropwdown by its id
var select = $("#ddlScheme");
$.ajax({
...
success: function (data) {
$.each(myJsonObject, function (i, mobj) {
$("#Cartbl").append('<tr><td width="50px">' + mobj.Description + '</td></tr>');
// for each element, add an option into the dropdown
select.append('<option>"+ mobj.Description +"</option>')
}
});
...
)}
See jsfiddle https://jsfiddle.net/n4mtj9om/
If use Chrome enter in developers tools a see how response the server put a breakpoint after server response because when use maybe
put this
function GetAllScheme() {
$.ajax({
type: "GET",
url: "http://localhost:32359/api/Claim",
dataType: "json",
success: function(data) {
$.each(data.responseJSON, function(i, mobj) {
$("#Cartbl").append('<tr><td width="50px">' + mobj.Description +
'</td></tr>');
});
},
error: function(xhr) {
alert(xhr.responseText);
}
});
}
I've checked around and read a couple articles on this issue and tried a few things but nothing seems to be working. The issue is when the button is clicked the first time nothing happens. The second time its clicked then the event and ajax request is fired off. In addition to having to click the button twice the ajax data is requested and displayed twice. Ive seen a few articles that said check the buttons visibility and if it is checking to turn off/on another elements visibility in this case its not. Additionally I have the onclick of the button calling a method to fire the ajax. Whats strange is when i removed the code from the method and place it in the DOM ready the event fires the first time but my ajax data never returns
Button HTML :
<input id="btnSearch" onclick="GetInfo();" type="button" value="Find ID" class="button-ffe" />
Here is the click code :
function GetInfo() {
var term = $('#txtUtente').val();
$('#btnSearch').click(function () {
var winW = window.innerWidth;
var winH = window.innerWidth;
var dialogoverlay = document.getElementById('dialogoverlay');
dialogoverlay.style.display = "block";
dialogoverlay.style.height = winH + "px";
$.ajax({
url: 'DAL/WebService1.asmx/GetPTSID',
method: 'post',
contentType: 'application/json;charset=utf-8',
data: JSON.stringify({ term: term }),
dataType: 'json',
success: function (data) {
document.getElementById('dialogoverlay').style.display = 'none';
$('#infoFoundID').html(data.d[0]);
$('#foundInfoMessage, #userInformation').show();
$('#registerProductInfo').hide();
var partTable = $('#partTable tbody');
$(data.d).each(function (index, id) {
partTable.append('<tr> <td>' + id + '</td><td>' + '<input onclick="GetPartNumber();" id="Button1" type="button" value="Copy Number" />' + '</td></tr>');
});
},
error: function (err) {
console.log(err);
}
});
});
} //end getinfo
You are attaching the event in the first click, so the code runs like you write.
You can remove the first function definition :
var term = $('#txtUtente').val();
$('#btnSearch').click(function () {
var winW = window.innerWidth;
var winH = window.innerWidth;
var dialogoverlay = document.getElementById('dialogoverlay');
dialogoverlay.style.display = "block";
dialogoverlay.style.height = winH + "px";
$.ajax({
url: 'DAL/WebService1.asmx/GetPTSID',
method: 'post',
contentType: 'application/json;charset=utf-8',
data: JSON.stringify({ term: term }),
dataType: 'json',
success: function (data) {
document.getElementById('dialogoverlay').style.display = 'none';
$('#infoFoundID').html(data.d[0]);
$('#foundInfoMessage, #userInformation').show();
$('#registerProductInfo').hide();
var partTable = $('#partTable tbody');
$(data.d).each(function (index, id) {
partTable.append('<tr> <td>' + id + '</td><td>' + '<input onclick="GetPartNumber();" id="Button1" type="button" value="Copy Number" />' + '</td></tr>');
});
},
error: function (err) {
console.log(err);
}
});
});
Your jQuery click function is in your GetInfo() function. Change your JS to:
var getInfo = {
init: function() {
$(document).ready( function() {
getInfo.click();
});
},
click: function() {
var term = $('#txtUtente').val();
$('#btnSearch').click(function () {
var winW = window.innerWidth;
var winH = window.innerWidth;
var dialogoverlay = document.getElementById('dialogoverlay');
dialogoverlay.style.display = "block";
dialogoverlay.style.height = winH + "px";
$.ajax({
url: 'DAL/WebService1.asmx/GetPTSID',
method: 'post',
contentType: 'application/json;charset=utf-8',
data: JSON.stringify({ term: term }),
dataType: 'json',
success: function (data) {
document.getElementById('dialogoverlay').style.display = 'none';
$('#infoFoundID').html(data.d[0]);
$('#foundInfoMessage, #userInformation').show();
$('#registerProductInfo').hide();
var partTable = $('#partTable tbody');
$(data.d).each(function (index, id) {
partTable.append('<tr> <td>' + id + '</td><td>' + '<input onclick="GetPartNumber();" id="Button1" type="button" value="Copy Number" />' + '</td></tr>');
});
},
error: function (err) {
console.log(err);
}
});
});
}
};
getInfo.init();
Now you can change your html to:
<input id="btnSearch" type="button" value="Find ID" class="button-ffe" />
That should work.
So, the first click will run GetInfo() - which, adds a jQuery click listener (but doesn't run it)
then the second click runs the function defined in the click listener - and GetInfo - which adds ANOTHER instance of the jQuery stuff
then the third click runs the function defined in the click listener, twice - and GetInfo - which adds ANOTHER instance of the jQuery stuff
use focusableInTouchMode=false in xml it works for me
This is my jQuery code to add html generated by a post in a div. The slidedown() function doesn't seem to be working right. Here is my script:
$(".expand").click(function(){
var button = $(this);
var id = $(this).attr("eid");
var url = "/get-complete/" + id + '/';
$.ajax({
type: "GET",
url: url,
success: function( data ) {
var obj = $.parseJSON(data);
var lang = '';
$.each(obj, function() {
lang += this['html'] + "<br/>";
});
button.siblings('.comment-expand').slideDown('slow', function(){
button.siblings('.comment-expand').html(lang);
});
button.attr('class', 'collapse');
button.html('Collapse');
},
});
return false;
});
Here is the html:
<a class="expand" href="/#" eid="{{ event.id }}">Expand</a>
<div class="comment-expand"></div>
This is the sample data returned by the GET request:
[{"html": "\n <div class=\"comment-count-bar\">\n</div>\n "}]
This is the code to collapse the post, but this isn't working either:
$("body").delegate(".collapse", "click", function(){
var button = $(this);
button.siblings('.comment-expand').slideUp('slow');
button.attr('class', 'expand');
button.html('Expand');
return false;
});
Try this:
$.ajax({
type: "GET",
url: url,
// setting the dataType to json, jQuery itself parses the response
dataType: 'json',
success: function(data) {
// Hiding the element and setting it's innerHTML
// before calling slideDown()
button.siblings('.comment-expand').hide().html(function() {
// Mapping the response and concatenating `html` properties
// If the response has only one array use:
// return data[0].html + '<br>'; instead
return $.map(data, function(v) {
return v.html + '<br>';
}).join('');
}).slideDown();
button.addClass('collapse')
.removeClass('expand')
.html('Collapse');
},
});
Edit: Since you are adding the class dynamically you should delegate the event:
$(document).on('click', '.collapse', function() {
// var button = $(this);
// ...
});
I want to pass the link on textbox blur function.
Jquery code
<a id="checkEmail" href="#" ></a> | <a id="getCandidate"></a> */* this is the link for get the profile details*/*
<script type ="text/javascript">
$('#getCandidate').text('Get Profile') // Sets text for email.
.attr('href', '#');
$("#Email").blur(function () {
$('#checkEmail').trigger('click');
//$('#checkEmail').trigger('GetCandidateDetail?validateEmail=' + $('#Email').val());
$('#getCandidate').text('Get Profile')
.attr('href', 'GetCandidateDetail?validateEmail=' + $('#Email').val());
});
$(document).ready(function () {
$('#checkEmail').click(function () {
var name = $('#Email').val();
var data = 'validateEmail=' + name;
$.ajax({
type: "GET",
url: "ValidateCandidate",
data: data,
success: function (data) {
alert(data);
}
});
return false;
});
});
</script>
Html code
<%: Html.TextBox("Email",Model.Email, new {#title="Enter the Candidate Email Id"})%>
<a id="checkEmail" href="#" ></a> | <a id="getCandidate"></a>
In the above code when I type the email id in textbox it triggers email id is registered or not. Then I give one more link getdetails. If I click that link then the profile will come by using the link GetCandidateDetail?validateEmail=' + $('#Email').val()).
But Now I want when I type the email id in textbox, if exists means it will load the link GetCandidateDetail?validateEmail=' + $('#Email').val())automatically otherwise false. How to do this? Help me to come out this issue?
You can do just like this:
$(document).ready(function() {
$("#Email").on('blur', function() {
// Check mail on blur
var email = $(this).val();
$.ajax({
type: "GET",
url: "ValidateCandidate",
data: {validateEmail:email},
success: function(data) {
// handle your response
}
});
});
});
function verify() {
var name = $('#Email').val();
var data = 'validateEmail=' + name;
$.ajax({
type: "GET",
url: "ValidateCandidate",
data: data,
success: function (data) {
alert(data);
return false;
});
}
$("#Email").blur(function(){verify();)
$("#checkEmail").click(function(){verify()})
thats it !!