I have passed the value of textbox to ajax using keyup(). But on emptying the textbox it displays all the contents from the relative table. I want an empty page while the textbox is empty. Can anyone help me with this problem. The codes are:
$('.form-control').keyup(function () {
var name = $('#member_search').val();
var phone = $('#member_contact').val();
var father = $('#member_father').val();
$.ajax({
type: "post",
url: "search_result.php",
data: {
name: name,
contact: phone,
father: father
},
success: function (data) {
$('#result').html(data);
}
});
});
Just check whether any one has content else empty the result box
$('.form-control').keyup(function () {
var name = $('#member_search').val();
var phone = $('#member_contact').val();
var father = $('#member_father').val();
if (name || phone || father) {//use name && phone && father if you want to make sure all inputs has content
$.ajax({
type: "post",
url: "search_result.php",
data: {
name: name,
contact: phone,
father: father
},
success: function (data) {
$('#result').html(data);
}
});
} else {
$('#result').html('');
}
});
Related
I'm a new developer asking my first SO question :). Working on a form that has some calculated fields based off corresponding text inputs in ASP.NET MVC. Essentially, takes value from text box, AJAX post that value to controller, perform calc, returns that data to read-only calculated field.
I have the following code for this working:
$("#volume").focusout(function () {
volume = $(this).val()
$.ajax({
type: "POST",
url: '/StaffingPlan/CalculatorAction',
data: { volume: volume },
dataType: "json",
success: function (data) {
console.log(data);
$("#selectorsNeeded").val(data);
}
});
});
$("#drops").focusout(function () {
drops = $(this).val()
$.ajax({
type: "POST",
url: '/StaffingPlan/CalculatorAction',
data: { drops: drops },
dataType: "json",
success: function (data) {
console.log(data);
$("#liftsNeeded").val(data);
}
});
});
and in the controller:
public ActionResult CalculatorAction(string volume, string drops)
{
int data = 0;
//one calculation performed for volume, but will be others to calculate
if (volume != null && volume != "")
{
data = Int32.Parse(volume) / 150 / 9;
}
//example of another calc
if (drops != null && drops != "")
{
data = Int32.Parse(drops) / 25 / 6;
}
return Json(data, JsonRequestBehavior.AllowGet);
}
This works, however, the form has several other inputs and calculated fields. Obviously there's better/dryer way to write this instead of duplicating the .focusout function. Would be nice to just get the field ID that changes and assign value to appropriate variable. Hope this makes sense! Any direction would be appreciated very much.
Change your code to this:
$("#volume").focusout(function () {
var data= { volume: $(this).val()},
var resultField= $("#selectorsNeeded");
calculateResult(data, resultField);
});
$("#drops").focusout(function () {
var data= { drops: $(this).val() },
var resultField= $("#liftsNeeded");
calculateResult(data, resultField);
});
function calculateResult (data, resultField) {
$.ajax({
type: "POST",
url: '/StaffingPlan/CalculatorAction',
data: data,
dataType: "json",
success: function (result) {
console.log(result);
resultField.val(result);
}
});
};
I have a JS function which takes a value from a textbox based on the Radio button selected.
Example: If RadioButton No is Selected, values is teken from TextBox A, else if RadioButton Yes is selected, Value is taken from TextBox B. The following script is in my view
$('#btnVolunteerSaveBtn').on('click', function() { // on click of save button
if (document.getElementById('RadioNo').checked) { //ID of radio button NO
var checking = $('#Donation').val(); //ID of textbox from where the value is to be taken if RadioButton No is selected
if (checking == "") {
//if nothing is entered, stop from saving in DB
} else {
x = $('#Donation').val(); //ID of textbox from where the value is to be taken if RadioButton No is selected
$.ajax({
url: '#Url.Action("DonationValue","VolunteerInfo")',
data: {
name: x
},
type: "POST"
});
}
} else {
x = $('#GetNames').val(); //ID of textbox from where the value is to be taken if RadioButton Yes is selected
$.ajax({
url: '#Url.Action("DonationValue","VolunteerInfo")',
data: {
name: x
},
type: "POST"
});
}
});
Till here it seems to work fine. Now coming to the controller, I have a function DonationValue
My Question:
How can I pass the name parameter above?
If nothing is filled in TextBox with id #Donation, how do I stop
from saving the form in the DB?
My Attempt:
I tried doing
public string DonationValue(string name = null)
{
return name; //Trying to pass this value above
}
This didn't help. It resolved the error but the passed value was always null. I also tried a couple of other things but none helped.
Edited:
[HttpPost]
public ActionResult AddVolunteer(VolunteerInfo viewModel)
{
if (!ModelState.IsValid)
{
return View("AddVolunteer", viewModel);
}
var volunteer = new VolunteerInfo()
{
Name = viewModel.Name,
BirthdayDateTime = viewModel.BirthdayDateTime,
Address = viewModel.Address,
PhoneNumber = viewModel.PhoneNumber,
EmailAddress = viewModel.EmailAddress,
OccasionsID = viewModel.OccasionsID,
DonationForWhom = _DonationValue
};
if (!string.IsNullOrEmpty(volunteer.DonationForWhom))
{
_context.VolunteerInfos.Add(volunteer);
_context.SaveChanges();
return RedirectToAction("Index", "Home");
}
return //something to save state so that user doesnt have to enter all the values again
}
[HttpPost]
public void DonationValue(string name)
{
_DonationValue = name;
}
#Daisy Shipton.
Is this a better solution?
<script>
$(function() {
$('#btnVolunteerSaveBtn').on('click', function() { // on click of save button
debugger;
if (document.getElementById('RadioNo').checked) { //ID of radio button NO
var checking = $('#Donation').val(); //ID of textbox from where the value is to be taken if RadioButton No is selected
if (checking == "") {
//if nothing is entered, stop from saving in DB
}
else {
var x = $('#Donation').val(); //ID of textbox from where the value is to be taken if RadioButton No is selected
var jsonObject = {
"textValue": x,
"isRadioSelected": "true" // show the radio is selected
};
$.ajax({
url: '#Url.Action("AddVolunteer", "VolunteerInfo")',
data: JSON.stringify(jsonObject),
contentType: "application/json; charset=utf-8",
dataType: "json",
type: "POST",
error: function (response) {
alert(response.responseText);
},
success: function (response) {
alert(response);
}
});
}
}
else {
var jsonObject2 = {
"textValue": $('#GetNames').val(),
"isRadioSelected": "false" // show the radio is not selected
};
$.ajax({
url: '#Url.Action("AddVolunteer", "VolunteerInfo")',
data: JSON.stringify(jsonObject2),
contentType: "application/json; charset=utf-8",
dataType: "json",
type: "POST",
error: function (response) {
alert(response.responseText);
},
success: function (response) {
alert(response);
}
});
}
});
})
</script>
In my controller:
[HttpPost]
public ActionResult AddVolunteer(VolunteerInfo volunteerInfo)
{
if (volunteerInfo.isRadioSelected)
{
//something
}
else
{
//something
return View();
}
1) Client calls to DonationValue post method with name paramter
e.g. name="abc"
[HttpPost]
public string DonationValue(string name = null) // name = "abc"
{
return name; //Trying to pass this value above
}
This returned value to be stored in client side say variable retunedDonationValue
If you don't pass any name parameter then above post method does return empty string then just set retunedDonationValue = ''
2) Now you have to pass above retunedDonationValue to your post method in posted json object like
var jsonObject =
{
"Name" = "YourName",
"BirthdayDateTime" = "YourBirthdayDateTime",
"Address" = "YourAddress",
"PhoneNumber" = "YourPhoneNumber",
"EmailAddress" = "YourEmailAddress",
"OccasionsID" = "YourOccasionsID",
"DonationForWhom" = retunedDonationValue //Note here
}
3) And pass this post data to http call to AddVolunteer
$.ajax({
url: '#Url.Action("AddVolunteer", "VolunteerInfo")',
data: JSON.stringify(jsonObject),
contentType: "application/json; charset=utf-8",
dataType: "json",
type: "POST",
error: function (response) {
alert(response.responseText);
},
success: function (response) {
alert(response);
}
});
4) And your action method is look like
[HttpPost]
public ActionResult AddVolunteer(VolunteerInfo viewModel)
{
if (!ModelState.IsValid)
{
return View("AddVolunteer", viewModel);
}
var volunteer = new VolunteerInfo()
{
Name = viewModel.Name,
BirthdayDateTime = viewModel.BirthdayDateTime,
Address = viewModel.Address,
PhoneNumber = viewModel.PhoneNumber,
EmailAddress = viewModel.EmailAddress,
OccasionsID = viewModel.OccasionsID,
DonationForWhom = viewModel.DonationForWhom
};
if (!string.IsNullOrEmpty(volunteer.DonationForWhom))
{
_context.VolunteerInfos.Add(volunteer);
_context.SaveChanges();
}
return View(viewModel);
}
Here I want to do which are the variable not empty, I want to pass that variable one in data,in this case area is empty so I want pass the parameter for city and listing type, but I don't know how to do?
var city = "Karnadaka";
var area = "";
var listing type = "RENT";
$.ajax({
type: 'GET',
url: "http://www.domain.com/api/get/searchProperties",
data: {
area: area,
city: city,
listingType: listing_type
},
success: function(data) {
console.log(data);
}
});
you can use delete to remove the propery pair(s) in an Object
var city = "Karnadaka";
var area = "";
var listing_type = "RENT";
var data={
area: area,
city: city,
listingType: listing_type
}
for (k in data){
if(data[k]=="") delete data[k];
}
$.ajax({
type: 'GET',
url: "http://www.domain.com/api/get/searchProperties",
data: data,
success: function(data) {
console.log(data);
}
});
Try this:
var city = "Karnadaka";
var area = "";
var listing_type = "RENT";
var data = {};
if(city != '')
data['city'] = city;
if(area != '')
data['area'] = area;
if(listing_type != '')
data['listing_type'] = listing_type;
$.ajax({
type: 'GET',
url: "http://www.domain.com/api/get/searchProperties",
data: data,
success: function(response) {
console.log(response);
}
});
I have two scripts, the first one loads a particular set of child nodes from an XML file via AJAX in order to render a menu in the form of a list of buttons in #loadMe. The great thing about this first script is that I have implemented the setInterval function which updates the list of buttons automatically anytime the XML file changes. The first script's rendered buttons are written to trigger the second script on mouse click, which renders a div filled with the desired node's sibling nodes in #toadMe. This second script also works, but only upon mouse click does it ensure updated data. In other words the setInterval function does not work on the second script because it is expecting a mouse click. How do I make the second script auto update if once it is displayed via mouse click?
setInterval(itemMenu,1500);
function itemMenu() {
$.ajax({
type: "GET",
url: "people.xml"
}).done(function (xml) {
$("#loadMe").empty();
$(xml).find('fullName').each(function() {
var fullName = $(this).text();
$('<button type="button" onclick="itemContent(this.value)"></button>').attr('value', fullName).html(fullName).appendTo('#loadMe');
});
}).fail(function (response, error) {
$('#info').text('Error!');
});
};
//setInterval(itemContent,1500);
function itemContent(q) {
$.ajax({
type: "GET",
url: "people.xml"
}).done(function (xml) {
$(xml).find('fullName').each(function() {
var fullName = $(this).text();
if(q==fullName) {
$("#toadMe").empty();
firstName = $(this).siblings('firstName');
lastName = $(this).siblings('lastName');
age = $(this).siblings('age');
hometown = $(this).siblings('hometown');
job = $(this).siblings('job');
$('<h1></h1>').html(firstName).appendTo('#toadMe');
$('<h1></h1>').html(lastName).appendTo('#toadMe');
$('<h1></h1>').html(age).appendTo('#toadMe');
$('<h1></h1>').html(hometown).appendTo('#toadMe');
$('<h1></h1>').html(job).appendTo('#toadMe');
}
});
}).fail(function (response, error) {
$('#info').text('Error!');
});
};
Is this what you want?
setInterval(itemMenu,1500);
function itemMenu() {
$.ajax({
type: "GET",
url: "people.xml"
}).done(function (xml) {
$("#loadMe").empty();
$(xml).find('fullName').each(function() {
var fullName = $(this).text();
$('<button type="button" onclick="itemContent(this.value)"></button>').attr('value', fullName).html(fullName).appendTo('#loadMe');
itemContent(fullName);
});
}).fail(function (response, error) {
$('#info').text('Error!');
});
};
//setInterval(itemContent,1500);
function itemContent(q) {
$.ajax({
type: "GET",
url: "people.xml"
}).done(function (xml) {
$(xml).find('fullName').each(function() {
var fullName = $(this).text();
if(q==fullName) {
$("#toadMe").empty();
firstName = $(this).siblings('firstName');
lastName = $(this).siblings('lastName');
age = $(this).siblings('age');
hometown = $(this).siblings('hometown');
job = $(this).siblings('job');
$('<h1></h1>').html(firstName).appendTo('#toadMe');
$('<h1></h1>').html(lastName).appendTo('#toadMe');
$('<h1></h1>').html(age).appendTo('#toadMe');
$('<h1></h1>').html(hometown).appendTo('#toadMe');
$('<h1></h1>').html(job).appendTo('#toadMe');
}
});
}).fail(function (response, error) {
$('#info').text('Error!');
});
};
Or you can create use another function so that you don't have to make another ajax call and something like this.
setInterval(itemMenu,1500);
function itemMenu() {
$.ajax({
type: "GET",
url: "people.xml"
}).done(function (xml) {
$("#loadMe").empty();
$(xml).find('fullName').each(function() {
var fullName = $(this).text();
$('<button type="button" onclick="itemContent(this.value)"></button>').attr('value', fullName).html(fullName).appendTo('#loadMe');
update($(this));
});
}).fail(function (response, error) {
$('#info').text('Error!');
});
};
function update(obj){
$("#toadMe").empty();
firstName = $(obj).siblings('firstName');
lastName = $(obj).siblings('lastName');
age = $(obj).siblings('age');
hometown = $(obj).siblings('hometown');
job = $(obj).siblings('job');
$('<h1></h1>').html(firstName).appendTo('#toadMe');
$('<h1></h1>').html(lastName).appendTo('#toadMe');
$('<h1></h1>').html(age).appendTo('#toadMe');
$('<h1></h1>').html(hometown).appendTo('#toadMe');
$('<h1></h1>').html(job).appendTo('#toadMe');
}//update
//setInterval(itemContent,1500);
function itemContent(q) {
$.ajax({
type: "GET",
url: "people.xml"
}).done(function (xml) {
$(xml).find('fullName').each(function() {
var fullName = $(this).text();
if(q==fullName) {
$("#toadMe").empty();
firstName = $(this).siblings('firstName');
lastName = $(this).siblings('lastName');
age = $(this).siblings('age');
hometown = $(this).siblings('hometown');
job = $(this).siblings('job');
$('<h1></h1>').html(firstName).appendTo('#toadMe');
$('<h1></h1>').html(lastName).appendTo('#toadMe');
$('<h1></h1>').html(age).appendTo('#toadMe');
$('<h1></h1>').html(hometown).appendTo('#toadMe');
$('<h1></h1>').html(job).appendTo('#toadMe');
}
});
}).fail(function (response, error) {
$('#info').text('Error!');
});
};
Here is a fiddle. http://jsfiddle.net/8xLk4/ Watch the last name. It will autoupdate.
I have the following javascript:
$('#edit_category').on('click','#btn_save_category_name',function(){
currently_edit.text($('#txt_edit_category').val());
edit_category_name(currently_edit,current_category_id);
$('#edit_category').modal('hide')
})
function edit_category_name(name, id){
$.ajax({
type: 'POST',
url: '/Category/edit_team_category',
dataType: 'json',
data: {
request: 'ajax',
name: name,
id: id
},
success: function (data) {
}
});
}
Now when i attempt this i get the following error: called 'click' called on an object that does not implement interface HTMLElement.
But if i comment the function line out aka : edit_category_name(currently_edit,current_category_id);
everything works fine.
Can anyone tell me why this is happening?
Update my full script
var mode = 'team';
var currently_edit = '';
var current_team_id = 0;
var current_category_id = 0;
jQuery(document).ready(function(){
//Main click function for Team (selection of team)
$('#team_wrapper').on('click', '.panel-heading', function () {
if(mode === 'team'){
current_team_id = $(this).siblings('small').text()
title = $(this).find('.text-white').text();
var i = 100;
$('#span_search').hide();
$('#btn_new_team').fadeOut();
$('.col-lg-3').each(function(){
$('.alt').toggle('slow');
$(this).fadeOut(300,function(){
$(this).remove();
});
});
$('#team_title').text('Select Category');
$('#btn_new_category').delay(500).fadeIn();
$('#selected_team_name').text(title);
$('#selected').delay(695).fadeIn();
$('#span_search').delay(500).fadeIn();
$('#back').delay(500).fadeIn();
generate_categories();
mode = 'category';
}else{
$(this).next('div').find('a')[0].click();
}
})
$('#team_wrapper').on('click', '.btn_administrate', function(){
current_team_id = $(this).next('.team_id').text();
load_team_members(current_team_id);
});
//Modal category:
//create
$('#btn_create_category').click(function(){
add_category($('#txt_create_category').val());
$('#group-form').modal('hide');
$('#txt_create_category').val('');
})
// edit
$('#team_wrapper').on('click','.team_category_edit',function(){
current_category_id= $(this).next('input').val()
edit_mode('txt_edit_category',$(this).closest("div").prev().find("h3"));
})
$('#edit_category').on('click','#btn_save_category_name',function(){
currently_edit.text($('#txt_edit_category').val());
edit_category_name(currently_edit,current_category_id);
$('#edit_category').modal('hide')
})
});
function edit_category_name(name, id){
$.ajax({
type: 'POST',
url: '/Category/edit_team_category',
dataType: 'json',
data: {
request: 'ajax',
name: name,
id: id
},
success: function (data) {
}
});
}
in this example:
var current_team_id = 1;
var current_category_id = 2;
What is the value of currently_edit? I am assuming this is a jQuery object not a text value. Try the following instead.
edit_category_name(currently_edit.text(),current_category_id);
Update
As Barmar mentioned, currently_edit.text(...) is invalid based on what you have shared. perhaps what you meant to do was:
currently_edit = $('#txt_edit_category').val();
Try changing this line currently_edit.text($('#txt_edit_category').val());
with this : currently_edit = $('#txt_edit_category').val();