jquery ajax: submit selected values from a form - asp.net-mvc

I have a form like this and i need to submit all values in this
form except those with class="noDisplay". Pass it to the
controller and update the value to "pd-price". Everything works fine, just that i cannot find a way to ignore the noDisplay values to submit the form.
<div class="cart">
<strong>
<span class="pd-price">80.407.000đ</span>
</strong>
</div>
<form method="post" id="product-details-form" action="xxx">
<ul>
<li class="showImg-target noDisplay">
<input type="radio" name="product_attribute_46_3_113"> [+3.870.000]
</li>
<li class="showImgtarget">
<input type="radio" name="product_attribute_46_4_113">[+1.000.000]</li>
<li class="showImgtarget noDisplay">
<input type="radio" name="product_attribute_46_5_113">[-1.500.000]</li>
<li class="showImgtarget noDisplay">
<input type="radio" name="product_attribute_46_6_113"></li>
..... a lot more
</ul>
</form>
<script type="text/javascript">
$(function () {
updateStatus();
$('*[name^=product_attribute]').change(function () {
updateStatus();
});
function updateStatus() {
$.ajax({
cache: false,
url: '/Catalog/UpdateProductStatus',
data: $('#product-details-form').serialize(),
type: 'post',
success: function (data) {
$('.summary-info').html(data.View);
$('.pd-price').html(data.Price);
$('.powered-icon').replaceWith(data.Pictures);
}
});
}
});
</script>

You can use :not() selector:
$('#product-details-form li:not(.noDisplay) :input').serialize();

Related

Checkbox dropdown won't stay down in ASP MVC

I figured out how to make a checkbox dropdown without using custom Javascript other than the bootstrap library for the dropdown button. No Javascript for handling the form data.:
http://plnkr.co/edit/NOM0UK2io6LaiJE5aSbs?p=preview
I have implemented this in an ASP-MVC view, but the behavior id different. In the ASP-MVC version, the dropdown pops back up after each checkbox selection. It's very annoying.
The ASP-MVC code is just the container div and its contents. Here is a live example, for as long as it stays up.
HTML + Bootstrap:
<!DOCTYPE html>
<html>
<head>
<meta name="viewport" content="width=device-width, initial-scale=1">
<link rel="stylesheet" href="http://maxcdn.bootstrapcdn.com/bootstrap/3.3.5/css/bootstrap.min.css">
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.3/jquery.min.js"></script>
<script src="http://maxcdn.bootstrapcdn.com/bootstrap/3.3.5/js/bootstrap.min.js"></script>
</head>
<body>
<div class="container">
<form action="http://yahoo.com" method="get" target="_blank">
<div class="dropdown">
<button class="btn btn-default dropdown-toggle" type="button" id="menu1" data-toggle="dropdown">Checkboxes
<span class="caret"></span></button>
<ul class="dropdown-menu" role="menu" aria-labelledby="menu1">
<li role="presentation"><input type="checkbox" name="cx1">cx1</li>
<li role="presentation"><input type="checkbox" name="cx2">cx2</li>
<li role="presentation"><input type="checkbox" name="cx3">cx3</li>
<li role="presentation"><input type="checkbox" name="cx4">cx4</li>
</ul>
</div>
<input type="submit" value="submit" class="btn btn-default">
</form>
</div>
</body>
</html>
Index.cshtml
#{
ViewBag.Title = "View";
Layout = "~/Views/Shared/_Layout.cshtml";
}
<div class="container">
<form action="http://yahoo.com" method="get" target="_blank">
<div class="dropdown">
<button class="btn btn-default dropdown-toggle" type="button" id="menu1" data-toggle="dropdown">
Checkboxes
<span class="caret"></span>
</button>
<ul class="dropdown-menu" role="menu" aria-labelledby="menu1">
<li role="presentation"><input type="checkbox" name="cx1" data-stoppropagation="true">cx1</li>
<li role="presentation"><input type="checkbox" name="cx2" data-stoppropagation="true">cx2</li>
<li role="presentation"><input type="checkbox" name="cx3" data-stoppropagation="true">cx3</li>
<li role="presentation"><input type="checkbox" name="cx4" data-stoppropagation="true">cx4</li>
</ul>
</div>
<input type="submit" value="submit" class="btn btn-default">
</form>
</div>
<script type="text/javascript">
$(function () {
$("ul.dropdown-menu").on("click", "[data-stopPropagation]", function (e) {
e.stopPropagation();
});
});
</script>
#section Scripts{
<script type="text/javascript">
$(function () {
$("ul.dropdown-menu").on("click", "[data-stopPropagation]", function (e) {
e.stopPropagation();
});
});
</script>
}
EDIT: offending Javascript
$(document).ready(function () {
getSpeciesList();
});
var current_path = window.location.pathname;
var current_controller = current_path.split('/')[1];
var species_select_url = "/" + current_controller + "/fillSpeciesSelect";
function getSpeciesList() {
console.log("in get species list");
$.ajax({
type: "GET",
url: url, // the method we are calling
contentType: "application/json; charset=utf-8",
dataType: "json",
data: "",
success: function (result) {
//alert("successfully got species list");
//alert(result[0]["SpeciesName"]);
fillSpeciesList(result);
},
error: function (result) {
//alert('Oh no aa :(' + result[0]);
}
})
}
function fillSpeciesList(species_list) {
console.log(species_list[0]["SpeciesName"]);
var species_select = $('.rreport-species-select');
for (var i = 0 ; i < species_list.length ; i++) {
//alert(species_list[i]["SpeciesName"]);
console.log(species_list[i]["SpeciesName"]);
species_select.append
(
"<li role='presentation'>" +
"<input type='checkbox' " +
"name='" + species_list[i]['SpeciesId'] + "' " +
"data-stoppropagation='true'" +
">" + species_list[i]['SpeciesName'] + "</li>" +
"</option>"
);
}
}
$('#species-select').on('change', function () {
var species_id = $('.report-species-select').val();
$('#variety-select').empty();
$.ajax({
type: "GET",
url: "/" + current_controller + "/fillVarietiesSelect", // the method we are calling
contentType: "application/json; charset=utf-8",
data: { "species_id": species_id },
dataType: "json",
success: function (result) {
fillVarietiesList(result);
},
error: function (result) {
alert('Oh no aa :(' + result[0]);
}
});
});
Referring to this answer Keep DropDown Open
Try this:
Add Script tag to whatever view you're working on
$(function () {
$("ul.dropdown-menu").on("click", "[data-stopPropagation]", function (e) {
e.stopPropagation();
});
});
As per the accepted answer add data-stoppropagation="true" to every checkbox element.
<input type="checkbox" name="cx1" data-stoppropagation="true">cx1</li>

unable to trigger select event on jquery autocomplete

i have a search form whith jquery autocomplete on some fields.
<form id="prjs_form" class="prjcts" action="<wp:action path="/ExtStr2/do/enpim/projects/list.action" />" method="post">
<div class="row bord">
<div class="wid_ut">
<span class="label"><wp:i18n key="ACRONYM" /></span>
<span class="field"><input id="autAcronym" type="text" name="bean.acronym" value="${bean.acronym}" class="lrg autocomplete" /></span>
</div>
......................
<div class="row">
<div class="act_btns">
<input type="submit" name="search" value="<wp:i18n key='SEARCH'/>">
</div>
</div>
</form>
My need is to submit the form when I select one of the values ​​suggested by autocomplete.
this is my jquery
jQuery('#autAcronym').autocomplete({
params: { type: 'project_acronym' },
paramName: 'text',
serviceUrl: '<wp:info key="systemParam" paramName="applicationBaseURL" />json/hall.ShowParameters',
minChars: 2,
select: function(event, ui) {
if(ui.item){
$(event.target).val(ui.item.value);
}
$('#prjs_form').submit();
return false;
}
});
when i start typing on field the autocomplete work fine, but when i select one of the suggested value the select event doesn't trigger....
what's wrong?
the other similar post on stackoverflow doesn't solved my problem
thanks in advance

How to passing form params from formRemote to remoteFunction in GSP

example is very simple.
select the two search condition and return a table with pagination, the whole page will not refresh.
so i use the grails formRemote to submit the form, and the control return the gender with template and it work well. However, the pagination i want to use Jquery, but i cant pass the formRemote params to the remoteFunction using onSuccess method in formRemote.
Here it is the code:
<div class="formSep col-md-12">
<g:formRemote update="searchResult" class="form-inline" role="form" name="form"
url="[controller: 'autoRateRecord', action: 'search']" onSuccess="initPagination(data)">
<div class="form-group col-lg-2">
<g:select class="form-control" name="notified" from="${['done', 'undone']}"
noSelection="${['null': 'Oops']}">
</g:select>
</div>
<div class="form-group col-lg-2 pull-right">
<button type="submit" class="btn btn-primary btn-lg">
<span class="glyphicon glyphicon-search"></span> search
</button>
</div>
</g:formRemote>
</div>
<div id="searchResult">
<g:render template="searchList"/>
</div>
<script type='text/javascript'>
function initPagination(data) {
console.log("------> " + data)
$("#Pagination").pagination(10, {
callback: getRecordList(1),
prev_text: "prev",
next_text: "next",
items_per_page: 15,
num_edge_entries: 1
});
}
**!!!!!!! need formRemote data !!!!!!!**
function getRecordList(page_index) {
<g:remoteFunction controller="autoRateRecord" action="search" update="searchResult" params="'page='+page_index"/>
}
// On load, style typical form elements
$(function () {
});
</script>
the controller code is:
def search = {
log.info(ToStringBuilder.reflectionToString(params))
// logic .....
render(template: "searchList", model: [
autoRateRecords: result,
total : result.totalCount
])
}
I would change the pagination script to something like
$("#pageHiddenFieldId").val(pageNo);
$("#myForm").submit();

jQuery Mobile and Knockout.js templating, styling isnt applied

Ok so this is beginning to drive me insane. I have for several hours now searched and searched, and every single solution doesnt work for me. So yes, this question might be redundant, but i cant for the life of me get solutions to work.
I have a bunch of checkboxes being generated by a jquery template that is databound via knockout.js. However, it turns up unstyled. Afaik, it is something about jquery mobile does the styling before knockout renderes the template, so it ends up unstyled.
I have tried numerous methods to no avail, so i hope someone here can see what i am doing wrong.
(i am using jquery mobile 1.2.0 , jquery 1.8.2 and knockout 2.2.1)
This is the scripts:
<script type="text/javascript">
jQuery.support.cors = true;
var dataFromServer = "";
// create ViewModel with Geography, name, email, frequency and jobtype
var ViewModel = {
email: ko.observable(""),
geographyList: ["Hovedstaden","Sjælland","Fyn + øer","Nordjylland","Midtjylland","Sønderjylland" ],
selectedGeographies: ko.observableArray(dataFromServer.split(",")),
frequencySelection: ko.observable("frequency"),
jobTypes: ["Kontor (administration, sekretær og reception)","Jura","HR, Ledelse, strategi og udvikling","Marketing, kommunikation og PR","Handel og service (butik, service, værtinde og piccoline)","IT","Grafik og design","Lager, chauffør, bud mv.","Økonomi, regnskab og finans","Kundeservice, telefoninterview, salg og telemarketing","Sprog","Øvrige jobtyper"],
selectedJobTypes: ko.observableArray(dataFromServer.split(",")),
workTimes: ["Fulltid","Deltid"],
selectedWorkTimes: ko.observableArray(dataFromServer.split(","))
};
// function for returning checkbox selection as comma separated list
ViewModel.selectedJobTypesDelimited = ko.dependentObservable(function () {
return this.selectedJobTypes().join(",");
}, ViewModel);
var API_URL = "/webapi/api/Subscriptions/";
// function used for parsing json message before sent
function omitKeys(obj, keys) {
var dup = {};
var key;
for (key in obj) {
if (obj.hasOwnProperty(key)) {
if (keys.indexOf(key) === -1) {
dup[key] = obj[key];
}
}
}
return dup;
}
//Function called for inserting new subscription record
function subscribe() {
if($("#jobmailForm").valid()=== true){
//window.alert("add subscriptiooncalled");
var mySubscription = ko.toJS(ViewModel);
//var json = JSON.stringify(mySubscription);
var jsonSmall = JSON.stringify(omitKeys(mySubscription, ['geographyList','jobTypes','selectedJobTypesDelimited','workTimes']));
//window.alert(jsonSmall);
$.ajax({
url: API_URL,
cache: false,
type: 'POST',
contentType: 'application/json',
data: jsonSmall,
success: function (data) {
window.alert("success");
},
error: function (error) {
window.alert("ERROR STATUS: " + error.status + " STATUS TEXT: " + error.statusText);
}
});
}
}
function initializeViewModel() {
// Get the post from the API
var self = this; //Declare observable which will be bind with UI
// Activates knockout.js
ko.applyBindings(ViewModel);
}
// Handle the DOM Ready (Finished Rendering the DOM)
$("#jobmail").live("pageinit", function() {
initializeViewModel();
$('#jobmailDiv').trigger('updatelayout');
});
</script>
<script id="geographyTmpl" type="text/html">
<input type="checkbox" data-role="none" data-bind="attr: { value: $data }, attr: { id: $data }, checked: $root.selectedGeographies" />
<label data-bind="attr: { for: $data }"><span data-bind="text: $data"></span></label>
</script>
<script id="jobTypeTmpl" type="text/html">
<label><input type="checkbox" data-role="none" data-bind="attr: { value: $data }, checked: $root.selectedJobTypes" /><span data-bind="text: $data"></span></label>
</script>
Note, "jobmail" is the surrounding "page" div element, not shown here. And this is the markup:
<div data-role="content">
<umbraco:Item field="bodyText" runat="server"></umbraco:Item>
<form id="jobmailForm" runat="server" data-ajax="false">
<div id="jobmailDiv">
<p>
<label for="email">Email</label>
<input type="text" name="email" id="email" class="required email" data-bind="'value': email" />
</p>
<fieldset data-role="controlgroup" data-mini="true" data-bind="template: { name: 'geographyTmpl', foreach: geographyList, templateOptions: { selections: selectedGeographies } }">
<input type="checkbox" id="lol" />
<label for="lol">fkfkufk</label>
</fieldset>
<fieldset data-role="controlgroup" data-mini="true">
<p data-bind="template: { name: 'jobTypeTmpl', foreach: jobTypes, templateOptions: { selections: selectedJobTypes } }"></p>
</fieldset>
<fieldset data-role="controlgroup" data-mini="true">
<input type="radio" id="frequency5" name="frequency" value="5" data-bind="checked: frequencySelection" /><label for="frequency5">Højst 5 gange om ugen</label>
<input type="radio" id="frequency3" name="frequency" value="3" data-bind="checked: frequencySelection" /><label for="frequency3">Højst 3 gange om ugen</label>
<input type="radio" id="frequency1" name="frequency" value="1" data-bind="checked: frequencySelection" /><label for="frequency1">Højst 1 gang om ugen</label>
</fieldset>
<p>
<input type="button" value="Tilmeld" class="nice small radius action button" onClick="subscribe();">
</p>
Tilbage
</div>
</form>
Alternate method of invoking the restyling (doesnt work either):
$(document).on('pagebeforeshow', '#jobmail', function(){
// Get the post from the API
var self = this; //Declare observable which will be bind with UI
// Activates knockout.js
ko.applyBindings(ViewModel);
});
// Handle the DOM Ready (Finished Rendering the DOM)
$("#jobmail").live("pageinit", function() {
$('#jobmail').trigger('pagecreate');
});
Use a custom binding (Knockout) to trigger jQuery Mobile to enhance the dynamically created content produced by Knockout.
Here is a simple custom binding:
ko.bindingHandlers.jqmEnhance = {
update: function (element, valueAccessor) {
// Get jQuery Mobile to enhance elements within this element
$(element).trigger("create");
}
};
Use the custom binding in your HTML like this, where myValue is the part of your view model that changes, triggering the dynamic content to be inserted into the DOM:
<div data-bind="jqmEnhance: myValue">
<span data-bind="text: someProperty"></span>
My Button
<input type="radio" id="my-id" name="my-name" value="1" data-bind="checked: someOtherProperty" /><label for="my-id">My Label</label>
</div>
In my own case, myValue was part of an expression in an if binding, which would trigger content to be added to the DOM.
<!-- ko if: myValue -->
<span data-bind="jqmEnhance: myValue">
<!-- My content with data-bind attributes -->
</span>
<!-- /ko -->
Every dynamically generated jQuery Mobile content must be manually enhanced.
It can be done in few ways, but most common one can be done through the jQuery Mobile function .trigger( .
Example:
Enhance only page content
$('#page-id').trigger('create');
Enhance full page (header + content + footer):
$('#page-id').trigger('pagecreate');
If you want to find more about this topic take a look my other ARTICLE, to be more transparent it is my personal blog. Or find it HERE.

Can we Made an anchor tag autoclick in the success function of Ajax Script?

Can we Made an anchor tag autoclick in the success function of Ajax Script?
Does it Possible we Click an anchor tag through Ajax Script?
if Yes then how?I am using Ajax in asp.net MVC?
This is the Viewsource of Partial View
<script language="javascript" type="text/javascript">
$(document).ready(function(){
alert("Button clicked");
$("#bt1").click(function(){
var data2 = $('#txt2').val();
var data1 = $('#Color').val();
$.ajax({
type:"Post",
url:'/Marker/CreateMarkerjson',
data:"Color="+ data1 + "&txt2=" + data2,
success:function(result)
{
alert(result);
$get('click').click();
},
error:function(result)
{
alert("fail");
}
});
});
});
</script>
<script type="text/javascript">
$(document).ready(function() {
$("#datepicker").datepicker();
});
</script>
<form action="/Marker/CreateMarkerPartial" method="post">
<fieldset>
<legend>Fields</legend>
<p>
<label for="Id" id="ID">
Id:</label>
<input type="text" id="txt1" />
</p>
<p>
<label for="CompanyName">
CompanyName:</label>
<input type="text" id="txt2" />
</p>
<p>
<label for="Color">
Color:</label>
<input id="Color" name="Color" type="text" value="" />
</p>
<p>
<input type="button" id="bt1" value="create" />
</p>
<div id="datepicker"></div>
</fieldset>
</form>
<div>
Back to List
click
</div>
Update answer. Merged the two $(document).ready functions and changed the $get('click') to $('#click'). Let's give it a try.
<script language="javascript" type="text/javascript">
$(document).ready(function () {
alert("Button clicked");
$("#bt1").click(function () {
var data2 = $('#txt2').val();
var data1 = $('#Color').val();
$.ajax({
type: "Post",
url: '/Marker/CreateMarkerjson',
data: "Color=" + data1 + "&txt2=" + data2,
success: function (result) {
alert(result);
$('#click').click();
},
error: function (result) {
alert("fail");
}
});
});
$("#datepicker").datepicker();
});
</script>
<form action="/Marker/CreateMarkerPartial" method="post">
<fieldset>
<legend>Fields</legend>
<p>
<label for="Id" id="ID">
Id:</label>
<input type="text" id="txt1" />
</p>
<p>
<label for="CompanyName">
CompanyName:</label>
<input type="text" id="txt2" />
</p>
<p>
<label for="Color">
Color:</label>
<input id="Color" name="Color" type="text" value="" />
</p>
<p>
<input type="button" id="bt1" value="create" />
</p>
<div id="datepicker">
</div>
</fieldset>
</form>
<div>
Back to List click
</div>
you can fire the click handler of the anchor tag that you want clicked.
for example:
<a id="clickme" href="somelink.html">Click me</a>
now there must be an event being fired from your ajax script on the successful completion of the request. In that function do
document.getElementById('clickme').click();

Resources