I'm using Ajax to add (and remove) multiple fields in a form, and then submitting them to mongoose to save them. Unfortunatelly I'm able to retrieve and save only 1 array, missing completely the dinamically added ones.
HTML: Here's a form with a form-group visible, where I inizialise the array using name attributes,and a form-group template that I dinamically populate with Ajax
<form id="productAdd" class="form-horizontal" method="post" enctype="multipart/form-data" action="?_csrf={{csrfToken}}">
<section class="panel">
<div class="panel-body">
<div class="form-group" data-option-index="1">
<label class="col-md-3 control-label" for="optionType">Type</label>
<div class="col-md-1">
<select class="form-control" name="options[0][optionType]">
<option value="grams">Gr.</option>
</select>
</div>
<label class="col-md-1 control-label" for="value">Value</label>
<div class="col-md-1">
<input type="text" class="form-control" name="options[0][optionValue]">
</div>
<label class="col-md-1 control-label" for="price">Price</label>
<div class="col-md-1">
<input type="text" class="form-control" name="options[0][optionPrice]">
</div>
<div class="col-md-1">
<button type="button" class="btn btn-default addButton"><i class="fa fa-plus"></i></button>
</div>
</div>
<div class="form-group hide" id="optionTemplate">
<label class="col-md-3 control-label" for="optionType">Type</label>
<div class="col-md-1">
<select class="form-control" name="optionType">
<option value="grams">Gr.</option>
</select>
</div>
<label class="col-md-1 control-label" for="value">Value</label>
<div class="col-md-1">
<input type="text" class="form-control" name="optionValue">
</div>
<label class="col-md-1 control-label" for="price">Price</label>
<div class="col-md-1">
<input type="text" class="form-control" name="optionPrice">
</div>
<div class="col-md-1">
<button type="button" class="btn btn-default removeButton"><i class="fa fa-minus"></i></button>
</div>
</div>
</div>
<footer class="panel-footer">
<div class="row">
<div class="col-sm-9 col-sm-offset-3">
<input type="hidden" name="_csrf" value="{{csrfToken}}">
<button class="btn btn-primary">Submit</button>
<button type="reset" class="btn btn-default">Reset</button>
</div>
</div>
</footer>
</section>
</form>
AJAX: I use this to add rows or remove them, each with 3 inputs. Before submitting the form I use .serialize() to get the arrays by their names
$(document).ready(function() {
var optionIndex = $(".form-group[data-option-index]").length;
$('#productAdd').submit(function(e) { // add product submit function
e.preventDefault();
$(this).ajaxSubmit({
contentType: 'application/json',
data: $('form[name="productAdd"]').serialize(),
error: function(xhr) {
console.log('Error: ' + xhr.status + ' ---- ' + xhr.responseText);
},
success: function(response) {
if (typeof response.redirect === 'string')
window.location = response.redirect;
}
});
return false;
})
// Add button click handler
.on('click', '.addButton', function() {
optionIndex++;
var $template = $('#optionTemplate'),
$clone = $template
.clone()
.removeClass('hide')
.removeAttr('id')
.attr('data-option-index', optionIndex)
.insertBefore($template);
// Update the name attributes
$clone
.find('[name="optionType"]').attr('name', 'options[' + optionIndex + '].optionType').end()
.find('[name="optionValue"]').attr('name', 'options[' + optionIndex + '].optionValue').end()
.find('[name="optionPrice"]').attr('name', 'options[' + optionIndex + '].optionPrice').end();
})
// Remove button click handler
.on('click', '.removeButton', function() {
var $row = $(this).parents('.form-group'),
index = $row.attr('data-option-index');
// Remove fields
$row.find('[name="options[' + index + '].title"]').remove();
$row.find('[name="options[' + index + '].isbn"]').remove();
$row.find('[name="options[' + index + '].price"]').remove();
// Remove element containing the fields
$row.remove();
});
});
NODEJS: Here's my nodejs route, I use multer for managing file upload. I've a foreach should manage the inputs from the form, but it just see the first element.
router.post('/shop/products/add', [isLoggedIn, multer({dest: './public/images/products/'}).single('productPhoto')], function(req, res, next) {
var newProduct = new Product();
newProduct.imagePath = req.file.filename;
newProduct.title = req.body.title;
newProduct.description = req.body.description;
newProduct.price = req.body.price;
newProduct.save()
.then(function (product) {
console.log(req.body.options);
req.body.options.forEach(function (option) {
var newOption = new ProductOption();
newOption.type = option.optionType;
newOption.value = option.optionValue;
newOption.price = option.optionPrice;
newOption.product = product;
newOption.save();
});
})
.then(function (options) {
req.flash('success', 'Product uploaded correctly.');
res.send({redirect: '/user/shop/products/add'});
})
.catch(function (err) {
console.log('Error ' + err.code + ': ', err.message);
res.status(500).send('Failed to save the newAddress to DB: ' + err);
});
});
It was a simple mistake, I named the fields dinamically added, differently from the static ones.
this code
.find('[name="optionType"]').attr('name', 'options[' + optionIndex + '].optionType').end()
should be like this
.find('[name="optionType"]').attr('name', 'options[' + optionIndex + '][optionType]').end()
Related
I'm trying to update my template without refreshing the page by ajax .... and I used two arrays for saving data permanently on front side and I send these two arrays with post method and ajax to my node js... I have some other input in my template but I don't want to send them with ajax ... How to parse them beside
ajax post?
my server
const express = require("express");
const bodyParser = require("body-parser");
const ejs = require("ejs");
const multer = require("multer");
const mongoose = require('mongoose');
const path = require("path");
const app = express();
var titlesList = [];
app.use(express.static("public"));
//if we wanna recive data from ajax we have to use this line
// var jsonParser = bodyParser.json();
// parse application/json
app.use(express.json());// add this line
app.use(bodyParser.urlencoded({ extended: false }));
var c = [];
var storage = multer.diskStorage({
destination:function(req,file,cb){
cb(null , "public/upload");
},
filename:function(req,file,cb){
cb(null , file.filename + '-' + Date.now() + path.extname(file.originalname));
}
});
var upload = multer ({
storage:storage
})
mongoose.connect("mongodb://localhost:27017/landingDb" , {useNewUrlParser : true} , { useUnifiedTopology: true } );
const courseSchema = new mongoose.Schema ({
courseTitle : String,
courseSubtitle : String,
coursreAuthor : String,
coursePrice : Number,
courseVideo : Object,
courseSpecs : Array,
courseTitles : Array,
courseValidation : Number,
courseTags : Array
});
const Courses = mongoose.model("Courses" ,courseSchema );
app.set("view engine", "ejs");
app.get("/cp" , function(req , res){
res.render("cp");
});
app.post("/cp" , upload.single("c_upload") , function(req , res){
var c_titles = [];
const c_specs = JSON.stringify(req.body.specs);
const file = req.file;
const c_title = req.body.c_title;
const c_subtitle = req.body.c_subtitle;
const c_creator = req.body.c_creator;
const c_price = req.body.c_price;
console.log(file);
console.log(JSON.stringify(req.body.titles));
console.log(JSON.stringify(req.body));
if(req.body.submitcp == "submitCp"){
console.log(file);
const courses = new Courses({
courseTitle:c_title,
courseSubtitle:c_subtitle,
courseAuthor : c_creator,
coursePrice : c_price,
courseVideo : file,
courseTitles : c_titles,
courseSpecs : c_specs,
courseValidation : 0
});
courses.save();
}
});
app.listen(3000, function () {
console.log("running");
});
my html
<%- include('header'); -%>
<div class="container-fluid">
<div class="row">
<div dir="rtl" class="col-md-6 cp_main_div">
<form action="/cp" enctype="multipart/form-data" class="titlesForm" id="form" method="post">
<div class="col-md-12">
<div class="form-group">
<label for="exampleInputEmail1">عنوان دوره</label>
<input name="c_title" type="text" class="form-control" id="exampleInputEmail1" aria-describedby="emailHelp" placeholder="...">
</div>
</div>
<div class="col-md-12">
<div class="form-group">
<label for="exampleInputEmail1">توضیحات مختصر دوره</label>
<input name="c_subtitle" type="text" class="form-control" id="exampleInputEmail1" aria-describedby="emailHelp" placeholder="...">
</div>
</div>
<div class="col-md-12">
<div class="form-group">
<label for="exampleInputEmail1">سازنده دوره</label>
<input name="c_creator" type="text" class="form-control" id="exampleInputEmail1" aria-describedby="emailHelp" placeholder="...">
</div>
</div>
<div class="col-md-12">
<div class="form-group">
<label for="exampleInputEmail1">قیمت دوره</label>
<input name="c_price" type="text" class="form-control" id="exampleInputEmail1" aria-describedby="emailHelp" placeholder="...">
</div>
</div>
<div class="col-md-12">
<div class="form-group">
<label for="exampleFormControlFile1">آپلود ویدیو معرفی</label>
<input name="c_upload" type="file" class="form-control-file videoup" id="fileupload">
</div>
</div>
<div class="col-md-12" >
<div class="c_preview_div">
<div class="video_play"></div>
<video class="c-preview-video">
<source src="assets/gm2.mp4" type="video/mp4">
Your browser does not support HTML video.
</video>
</div>
</div>
<div class="col-md-12">
<div class="form-group">
<label for="exampleInputEmail1">نوع دوره</label>
<select name="c_type" class="form-control form-control-lg">
<option>وبینار</option>
<option>دوره آنلاین</option>
<option>دوره آفلاین</option>
<option>ورکشاپ</option>
<option>دوره فیزیکی</option>
</select>
</div>
</div>
<div class="col-md-12">
<div class="form-group">
<label for="exampleInputEmail1">عنوان های دوره</label>
<input name="titlesInput" id="titlesInp" type="text" class="form-control cp_input_titles" id="exampleInputEmail1" aria-describedby="emailHelp" placeholder="...">
</div>
<button id="title_submit" name="addTitles" value="addtitles" type="clickspecs_submit" class="btn btn-primary mb-2 add_titles">+</button>
<div style="width: 100%; height: 100%;" id="showTitles">
</div>
</div>
<div class="col-md-12">
<div class="form-group">
<label for="exampleInputEmail1">مشخصات دوره</label>
<input name="specsInput" id="c_specs" type="text" class="form-control cp_input_titles" id="exampleInputEmail1" aria-describedby="emailHelp" placeholder="...">
</div>
<button id="specs_submit" name="addSpecs" value="addspecs" type="click" class="btn btn-primary mb-2 add_titles">+</button>
<div style="width: 100%; height: 100%;" id="showSpecs">
</div>
</div>
<div class="col-md-12">
<div class="form-group">
<label for="exampleInputEmail1">تگ ها</label>
<select name="c_type" class="form-control form-control-lg">
<option>وبینار</option>
<option>دوره آنلاین</option>
<option>دوره آفلاین</option>
<option>ورکشاپ</option>
<option>دوره فیزیکی</option>
</select>
</div>
</div>
<div class="col-md-12">
<button type="submit" name="submitcp" value="submitCp" id="submitpostCp" class="btn btn-primary btn-lg btn-block">send</button>
</div>
</div>
</form>
<!-- <iframe id="uploader_iframe" name="uploader_iframe" style="display: none;"></iframe> -->
</div>
</div>
</div>
</body>
<footer>
</footer>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.5.1/jquery.min.js"></script>
</script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/popper.js/1.12.9/umd/popper.min.js"
integrity="sha384-ApNbgh9B+Y1QKtv3Rn7W3mgPxhU9K/ScQsAP7hUibX39j7fakFPskvXusvfa0b4Q" crossorigin="anonymous">
</script>
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0/js/bootstrap.min.js"
integrity="sha384-JZR6Spejh4U02d8jOt6vLEHfe/JQGiRRSQQxSfFWpi1MquVdAyjUar5+76PVCmYl" crossorigin="anonymous">
</script>
<script charset="utf-8" src="https://cdnjs.cloudflare.com/ajax/libs/OwlCarousel2/2.3.4/owl.carousel.min.js"></script>
<script type="text/javascript" charset="utf-8" src="script.js"></script>
<script type="text/javascript" charset="utf-8" src="sort.js"></script>
<script type="text/javascript" src="lightslider.js"></script>
</html>
my ajax call
var titlesLis = [];
var specsLis = [];
document.getElementById("form").addEventListener("submit", function (e) {
e.preventDefault();
e.stopPropagation();
//check what btn submit and push to item to array
if (e.submitter.id == "title_submit") {
var titlesInp = $(".cp_input_titles").val();
titlesLis.push(titlesInp);
}
//check what btn submit and push to item to array
if (e.submitter.id == "specs_submit") {
var specsInp = $("#c_specs").val();
specsLis.push(specsInp);
}
//check what btn submit and remove item from array
//check what btn submit and delete the item from view
if (e.submitter.id == "delete_specs") {
if(e.submitter.id >="0"){
specsLis.splice(e.submitter.id , 1);
}
$("#" + 'specs' + e.submitter.value).remove();
showspecItems();
}
//check what btn submit and remove item from array
//check what btn submit and delete the item from view
if (e.submitter.id == "delete_titles") {
if(e.submitter.id >="0"){
titlesLis.splice(e.submitter.id , 1);
}
$("#" + 'titles' + e.submitter.value).remove();
showtitleItems();
}
var data = {};
data.titles = titlesLis;
data.specs = specsLis;
//ajax call
$.ajax({
type: 'post',
url: '/cp',
data: JSON.stringify(data),
contentType: 'application/json',
xhrFields: {
withCredentials: false
},
headers: {
},
success: function (data) {
console.log('Success');
console.log(data);
//check what btn submit and delete the item from view
if (e.submitter.id == "title_submit") {
showtitleItems();
}
if (e.submitter.id == "specs_submit") {
showspecItems();
}
},
error: function () {
console.log('We are sorry but our servers are having an issue right now');
}
})
function showtitleItems() {
$("#showTitles").empty();
for (var i = 0; titlesLis.length > i; i++) {
$("#showTitles").append('<div id="' + 'titles' + i + '" class="TSShow titlesShow"><button name="deleteTitles" value="' + i + '" type="submit" id="delete_titles">-</button><h4>' + titlesLis[i] + '</h4></div>');
}
}
function showspecItems() {
$("#showSpecs").empty();
for (var i = 0; specsLis.length > i; i++) {
$("#showSpecs").append('<div id="' + 'specs' + i + '" class="TSShow specsShow"><button name="deleteSpecs" value="' + i + '" type="submitz" id="delete_specs">-</button><h4>' + specsLis[i] + '</h4></div>');
}
}
})
I have a form with some fields and after submit finish i want to reset whole form but only reset input text areas not input type file.
I check every similar questions and solutions but none of them work for me.Some solutions refresh page which i don't want that.
<form class=" dropzone px-5" id="mydropzone">
<h2 class="text-center">Lets create your menu</h2>
<div class="form-row">
<div class="form-group col-md-6">
<label for="inputCalories">Calorie</label>
<input type="text" class="form-control" id="inputCalories" required>
</div>
<div class="form-group col-md-6">
<label for="cc">Calorie Calculator</label>
<button id="cc" class="btn btn-primary btn-lg"><i class="fas fa-calculator mr-2"></i>Click Me</button>
</div>
</div>
<div class="form-row">
<div class="form-group ml-2 col-sm-6">
<label>Menu Item Image</label>
<div id="msg"></div>
<div class="progress" id="uploader">
<div class="progress-bar progress-bar-striped progress-bar-animated" role="progressbar" aria-valuenow="10" aria-valuemin="0" aria-valuemax="100" style="width: 10%"></div>
</div>
<input type="file" name="img[]" class="file" accept="image/*" id="fileButton">
<div class="input-group my-3">
<input type="text" class="form-control" disabled placeholder="Upload File" id="file" required>
<div class="input-group-append">
<button type="button" class="browse btn btn-primary"><i class="fas fa-folder-open mr-2"></i>Browse...</button>
</div>
</div>
<div class="ml-2 col-sm-6">
<img src=" " id="preview" class="img-thumbnail">
</div>
</div>
</div>
<button type="submit" class="btn btn-primary btn-block mb-3">Submit Menu</button>
<!-- -------------------------------------------------------------------------- -->
</div>
</form>
And my create menu which clear all fields after form submit.
// create menu
var uploader = document.getElementById('uploader');
var fileButton = document.getElementById('fileButton');
fileButton.addEventListener('change', function(e) {
var file = e.target.files[0];
var storageRef = firebase.storage().ref('foodImg/' + file.name);
var task = storageRef.put(file);
task.on('state_changed', function progress(snapshot) {
var percentage = (snapshot.bytesTransferred / snapshot.totalBytes) * 100;
uploader.value = percentage;
}, function(error) {
console.error(error);
}, function() {
task.snapshot.ref.getDownloadURL().then(function(downloadURL) {
console.log('File available at', downloadURL);
const createMenuForm = document.querySelector('#mydropzone');
createMenuForm.addEventListener('submit', (e) => {
e.preventDefault();
db.collection('restaurants').add({
foodLine: {
menuTitle: createMenuForm.menuTitle.value
},
food: {
foodName: createMenuForm.foodName.value,
imageURL: downloadURL,
inputCalories: createMenuForm.inputCalories.value,
menuItemDescription: createMenuForm.menuItemDescription.value,
menuItemInfo: createMenuForm.menuItemInfo.value
}
}).then(() => {
//reset form
createMenuForm.reset();
fileButton.value = "";
var preview = document.getElementById('preview');
preview.value = "";
}).catch(err => {
console.log(err.message);
});
});
});
});
});
Can you try these things also
document.getElementById("myForm").reset();
$("#myForm").trigger("reset");
I think you try to access createMenuForm outside the scope where const createMenuForm was declared.
Try to declare it above the event listener:
// create menu
const createMenuForm = document.querySelector('#mydropzone');
var uploader = document.getElementById('uploader');
var fileButton = document.getElementById('fileButton');
// ...
or directly with
document.querySelector('#mydropzone').reset();
i debug and find that preview need to be clean
document.getElementById("preview").src = "#";
I am trying to get .sortable from jQuery UI to work but it is only working for my first item, when I dynamically add new ones, it stops working.
I found this: http://api.jqueryui.com/sortable/#method-refresh which should refresh everything and recognize new items, but when I use that I get the error:
Uncaught Error: cannot call methods on sortable prior to initialization; attempted to call method 'refresh'
What can I do?
My code:
// HTML template for new fields
const template = `<div class="row sortwrap">
<div class="col-md-8">
<input type="text" name="category[]" placeholder="" class="form-control name_list catinput" />
<i class="mdi mdi-sort dragndrop"></i>
<div class="questionlist">
<div class="row">
<div class="col-md-8">
<input type="text" name="question[]" placeholder="1. Voeg een vraag toe" class="form-control name_list questioninput" />
</div>
<div class="col-md-4">
<button class="btn btn-success questionbutton">Extra vraag</button>
</div>
</div>
</div>
</div>
<div class="col-md-4">
<button id="addcategory" class="btn btn-danger btn_remove">X</button>
</div>
</div>`;
const vraagTemplate = `<div class="row">
<div class="col-md-8">
<input type="text" name="question[]" class="form-control name_list questioninput" />
</div>
<div class="col-md-4">
<button class="btn btn-danger btn_remove">X</button>
</div>
</div>`;
$('.sortwrap').sortable();
// Count numbers and change accordingly when field is deleted
function updatePlaceholders() {
// Sortable code
$('.sortwrap').sortable("refresh");
$('#dynamic_field input[name^=cat]').each(function(i) {
$(this).attr("placeholder", i + 1 + ". Voeg een categorie toe");
});
$('#dynamic_field .sortwrap').each(function(i) {
$(this).attr("id", i + 1);
});
$('#dynamic_field .questionlist').each(function() {
$(this).find('input[name^=qu]').each(function(i) {
$(this).attr("placeholder", i + 1 + ". Voeg een vraag toe");
});
});
}
// Append category template
$('#addcategory').click(function() {
$('#dynamic_field').append($(template));
updatePlaceholders();
});
// Append question template
$('#dynamic_field').on('click', '.questionbutton', function() {
$ql = $(this).closest('.questionlist');
$ql.append($(vraagTemplate));
updatePlaceholders();
});
// Delete
$('#dynamic_field').on('click', '.btn_remove', function() {
$(this).closest('.row').remove();
updatePlaceholders();
});
If I remove the line that says refresh in my function and only have the one .sortable in my code then I can drag all items even new ones but nothing is dropping. So I can drag but not sort/drop.
I think this is on where you attach your sort. I used a wrapper here to do so.
Note I turned off the refresh due to where I attached it as it seems to not need that given that attachment point.
// HTML template for new fields
const template = '<div class="row sortwrap"> <div class="col-md-8"> <input type="text" name="category[]" placeholder="" class="form-control name_list catinput" /> <i class="mdi mdi-sort dragndrop"></i> <div class="questionlist"> <div class="row"> <div class="col-md-8"> <input type="text" name="question[]" placeholder="1. Voeg een vraag toe" class="form-control name_list questioninput" /> </div> <div class="col-md-4"> <button class="btn btn-success questionbutton">Extra vraag</button> </div> </div> </div> </div> <div class="col-md-4"> <button id="addcategory" class="btn btn-danger btn_remove">X</button> </div> </div>';
const vraagTemplate = '<div class="row"> <div class="col-md-8"> <input type="text" name="question[]" class="form-control name_list questioninput" /> </div> <div class="col-md-4"> <button class="btn btn-danger btn_remove">X</button> </div> </div>';
// Count numbers and change accordingly when field is deleted
function updatePlaceholders() {
// Sortable code
// $('#dynamic_field').sortable( "refresh" );
let df = $('#dynamic_field');
df.find('input[name^=cat]').each(function(i) {
$(this).attr("placeholder", i + 1 + ". Voeg een categorie toe");
});
df.find('.sortwrap').each(function(i) {
$(this).attr("id", i + 1);
});
df.find('.questionlist').each(function() {
$(this).find('input[name^=qu]').each(function(i) {
$(this).attr("placeholder", i + 1 + ". Voeg een vraag toe");
});
});
}
// Append question template
$('#dynamic_field').on('click', '.questionbutton', function() {
let $ql = $(this).closest('.questionlist');
$ql.append($(vraagTemplate));
updatePlaceholders();
});
// Delete
$('#dynamic_field').on('click', '.btn_remove', function() {
$(this).closest('.row').remove();
updatePlaceholders();
});
$('#addcategory').on('click', function() {
let t = $(template)
$('#dynamic_field').append(t);
updatePlaceholders();
});
$(function() {
$('#addcategory').trigger('click');
$('#dynamic_field').sortable();
});
.sortwrap{border: solid green 1px;}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<link rel="stylesheet" href="https://ajax.googleapis.com/ajax/libs/jqueryui/1.12.1/themes/smoothness/jquery-ui.css">
<script src="https://ajax.googleapis.com/ajax/libs/jqueryui/1.12.1/jquery-ui.min.js"></script>
<div>
<button id="addcategory">add</button>
</div>
<div id="dynamic_field"></div>
As mentioned above this will work fine
This looks promising:
http://api.jqueryui.com/sortable/#method-refresh
it seems to imply that you can just add an item to a sortable, then call
$('#mysortable').sortable('refresh')
to recognize it.
var counter = 1;
function appendThing() {
$("<li id='Text" + counter + "' class='ui-state-default'>Text" + counter + "</li>").appendTo($("#mySortable"));
$("#mySortable").sortable({ refresh: mySortable })
counter++;
};
please take a look into this
https://jsfiddle.net/6ztrdg9n/
I have a webform with several fields I want to capture in an object and send it to a controller method. The form has this code:
<div class="panel-footer">
#using (Html.BeginForm("NuevaOpcion", "Home", FormMethod.Post, new { #id = "frm_nueva_opcion" })) {
#Html.HiddenFor(m => m.Id)
<div class="row">
<div class="col-md-6">
<div class="form-group" style="margin-bottom: .7em;margin-top: .7em;">
<button class="btn btn-success btn-xs" type="button" onclick=" $('#row-nueva-opcion').toggle()" id="add-opcion">
<span class="glyphicon glyphicon-plus-sign"></span> Añadir nueva opción
</button>
</div>
</div>
</div>
<div class="row" id="row-nueva-opcion" style="display:none">
<div class="col-md-10">
<label>
<input type="checkbox" id="opcion-extra" onclick=" $('#nuevo-precio').attr('disabled', !this.checked);" />
Es opción extra
</label>
<div class="input-group" style="margin-bottom:1.7em;">
<input type="text" placeholder="Opción" class="form-control" name="nombre" style="max-width:70%;">
<input type="number" placeholder="Cantidad" min="1" value="1" class="form-control" name="cantidad" style="max-width:15%;">
<input type="number" placeholder="Precio" class="form-control" id="nuevo-precio" name="precio" style="max-width:15%;" disabled>
<input type="hidden" name="idrespuesta" id="idrespuesta" value="#listItems.Select(x=>x.Value).FirstOrDefault()" />
<div class="input-group-addon">€</div>
<span class="input-group-btn">
<a class="btn btn-primary" data-title="Confirmación de acción" data-toggle="modal" data-target="#modal_confirm" onclick="confirmar('frm_nueva_opcion')">
<span class="glyphicon glyphicon-floppy-disk"></span> Guardar
</a>
</span>
</div>
</div>
<div class="col-md-8">
<div class="form-group">
<label>
¿Para que pregunta es la opción?
#Html.DropDownList("OptionSelectedItem", listItems, new { #class = "form-control" })
</label>
</div>
</div>
</div>
}
</div>
To manage it, I have a script that looks like this:
function mostrarModal(idmodal, mensaje, tipo) {
$(idmodal + ' .modal-body h4').addClass(tipo == 'error' ? 'text-danger' : 'text-secondary').html(mensaje);
$(idmodal).modal('show');
}
function enviar(form) {
debugger;
var NuevoPrecio = $('#' + form).attr("nuevo-precio");
if( (NuevoPrecio == null) || (typeof NuevoPrecio === "undefined") ) { var NuevoPrecio = 0; }
var datos = {
Id: $('#' + form).attr("#Id"),
IdPresupuestador: $('#' + form).attr("#idPresupuestador"),
IdRespuesta: $('#' + form).attr("#idrespuesta"),
Cantidad: $('#' + form).attr("#cantidad"),
Nombre: $('#' + form).attr("#nombre"),
Precio: NuevoPrecio,
}
$.post("NuevaOpcion", {
contentType: 'application/json; charset=utf-8',
data: JSON.stringify(datos),
});
}
var modalConfirm = function (callback) {
$("#modal-btn-si").on("click", function () {
callback(true);
$("#modal-confirm").modal('hide');
});
$("#modal-btn-no").on("click", function () {
callback(false);
$("#modal-confirm").modal('hide');
}); };
function confirmar(form, text) {
$("#modal-confirm").modal('show');
modalConfirm(function (confirm) {
if (confirm) {
enviar(form);
}
}); };
Trouble is, I've changed the script on several points and now looks like this because the best I could manage was taking all the form in a single object. I can't work with the properties contained in that object, not on the script and neither on the controller method.
So, the question is, how am I selecting the fields wrong? I've tried with "#", ".", just the name between quotes, and as I said, the best I could get was the entire form in a single object. Thanks in advance.
I have an $.ajax() request working properly and it's calling 3 ids. The only id with no issues is the name id. The clientId logs well on the console, but prints undefined on the table. The url is printing [object HTMLInputElement] on the table and on the console, logs like this<input class="form-control no-border" type="text" id="redirectUrl" name="url" placeholder="http://stuffpage/redirect/?id=1" required="">.I want to print the url that i am introducing on the input.
Can you tell me what is the problem?
$('#saveButton').on('click', function() {
var url = "http://stuffpage.com/redirect/redirect";
var name = $('#name').val();
console.log("name", name);
var clientId = $('#clientId').val();
console.log("clicentId", clientId);
var redirecUrl = $('#redirectUrl').val();
console.log("redirectUrl", redirectUrl);
var formData = new FormData();
formData.append('name', name);
formData.append('client_id', clientId);
formData.append('url', redirectUrl);
console.log('test')
$.ajax({
url: url + "/saveRedirect",
type: "POST",
dataType: "json",
data: formData,
contentType: false,
cache: false,
processData: false,
success: function(obj) {
var name, clientId, redirecUrl;
var rows = '';
for (i = 0; i < obj.length; i++) {
rows += "<tr class='lightgrey'><th>" + obj[i].name + "</th><td>" + obj[i].clientId + "</td><td>" + obj[i].url + "</td><td><img id='editButton' class='col-md-2 edit nopad' src='http://stuffpage.com/redirect/public/img/edit.svg'><img class='col-md-2 link nopad float-right' src='http://stuffpage.com/redirect/public/img/copy.svg'></td></td></tr>";
$("#table").append(rows);
console.log('sucess!');
}
},
error: function() {
console.log('error');
}
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.1.1/jquery.min.js"></script>
<div class="col-md-12 marg-t-30 nopad">
<!--REGISTER NAME CLIENT ID URL-->
<div class="col-md-1 nopad">
<div class="rtitle">
<div class="roboto-condensed">name</div>
</div>
</div>
<div class="col-md-3 nopad" style="margin-right: 20px;">
<input class="form-control no-border" id="name" type="text" name="nameClient" placeholder="Insert name..." required="">
</div>
<div class="col-md-1 nopad">
<div class="rtitle">
<div class="roboto-condensed">client id</div>
</div>
</div>
<div class="col-md-3 nopad">
<select class="form-control no-border selectpicker" name='clientId' id='clientId' data-show-subtext="true" required="">
<?php echo $client_data;?>
</select>
</div>
<div class="col-md-3 nopad">
<button id="saveButton" class="save float-right">SAVE</button>
</div>
<div class="col-md-12 nopad marg-t-20">
<div class="col-md-1 nopad">
<div class="rtitle">
<div class="roboto-condensed">url</div>
</div>
</div>
<div class="col-md-11 nopad">
<input class="form-control no-border" type="text" id="redirectUrl" name="url" placeholder="http://stuffpage/redirect/?id=1" required="" value="">
</div>
</div>
</div>
<!--col-md-12-->
Looks like you have a typo:
var redirecUrl = $('#redirectUrl').val();
should be
var redirectUrl = $('#redirectUrl').val();
You can replace
var clientId = $('#clientId').val();
To
var clientId = $('#clientId option:selected').val();
And
var redirectUrl = $('#redirectUrl').val();