i have a form where i get a collection of records, and after being present is shown like this:
<input name="position" id="nameText" step-id="3" type="number" value="1" class="form-control stepinput">
<input name="position" id="nameText" step-id="4" type="number" value="2" class="form-control stepinput">
<input name="position" id="nameText" step-id="5" type="number" value="3" class="form-control stepinput">
The value is to later sort the records, and the "step_id" attribute is to send via ajax to update the specific record, but my data is not quite looking good. Wich is the best way to send my data to the controller to later being updated the records
My current code:
$('button.update-positions').on('click', function(event){
event.preventDefault();
var form = $(this).closest(".steps-form");
var map = {};
$(".stepinput").each(function() {
map[$(this).attr("step-id")] = $(this).val()
});
})
Hard to read but if I understood correctly you:
Have an 3 inputs of numbers
Want the value entered being updated in the Database
use "step-id" to identify which one to update
If so then replace step-id="" by data-stepid="" and the code for that would be:
$("button.update-positions").on("click",function(event) {
event.preventDefault();
var form = $(this).closest(".steps-form");
var map = {};
$(".stepinput").each(function(index,value) {
map[$(this).data("stepid")] = value.value;
});
console.log(map); // Your map object
});
You can't have 2 elements with the same ID and you should use a data-attribute if you want to pass on information like so.
Related
I have validated it to send one or two or all three if the user checks the checkbox. My problem is I only receive one value even if the user checks all three.
This is is on laravel php framework, but I think it applies to all database logic.
This is MySQL data type
$table->string('category');
function restorative() {
var x = document.getElementById("restorative").required;
}
function esthetics() {
var x = document.getElementById("esthetics").required;
}
function implant() {
var x = document.getElementById("implant").required;
}
<input type="checkbox" name="category" value="Restorative" id="restorative" onclick="restorative()"><label for="">Restorative</label>
<br>
<input type="checkbox" name="category" value="Esthetics" id="esthetics" onclick="esthetics()"><label for="">Esthetics</label>
<br>
<input type="checkbox" name="category" value="Implants" id="implants" onclick="esthetics()"><label for="">Implants</label>
Use an array with name="category[]" then you will have a $_POST['category'] then before save use json_encode($_POST['category']) which covert array to string. Later you can json_decode($data) to get original array. Thanks
I know this question has being done here a lot but I looked and tried a lot of answers, wasn't able to retrieve what i need.
First, I pass a value from an item using django forms through the view. In this example, the template receive the value of "900" because I use the default {{form.price}} in HTML .
<input type="text" name="price" value="900" readonly="readonly" id="id_price">
Inside the same HTML i have a field to manually insert a quantity:
<input type="text" name="quantity" id="quantity">
And the final input to show to multiplication between those two
<input type="text" name="total" id="total">
As a script I used this (saw the answer in a question but i wasn't able to recreate the result in my "total" input)
SCRIPT
<script>
$(document).ready(function () {
$('').keyup(function () {
var multiplyAndShow = function () {
var val1 = parseFloat($('#id_price').val())
var val2 = parseFloat($('#quantity').val())
val3 = val1 * val2 || "Some Text"
$("#total").html(val3)
}
$("#id_price").keyup(function () { multiplyAndShow(); });
$("#quantity").keyup(function () { multiplyAndShow(); });
});
});
</script>
The script is not been used because when I set a quantity it doesn't make a thing in real time. The price value is readonly so i don't know if that's the problem.
I'm a newbie in javascript so any help will be appreciated
You should set the value of the total field, not the html. Change the following line
$("#total").html(val3)
to
$("#total").val(val3)
You should also change the $('') to $(document).
There are checkboxes, which belong to Form A:
<input type="checkbox" class="item-selector" name="item[]" value="1" />
<input type="checkbox" class="item-selector" name="item[]" value="2" />
<input type="checkbox" class="item-selector" name="item[]" value="3" />
<!-- etc. -->
Then I have Form B that needs the checkbox values from Form A. Form A might have other input fields too, but I'm not interested in those. I only care about $('input.item-selector'). I'm going about it like this:
var postData = $('#form-a').serializeArray();
var items = $('.item-selector:checked').map(function(){
return this.value;
}).get();
if(items.length > 0) {
postData.push({name: 'itemId', value: items});
}
But this way of adding stuff to the postData doesn't seem to work, because the PHP script I send the form to can not find the itemId. Interestingly this does work:
postData.push(name: 'aName', value: 'notAnArrayButAStringValue');
I also tried a couple of solutions like this one: http://benalman.com/projects/jquery-misc-plugins/#serializeobject but the problem with them is that, while they otherwise work fine, for some reason if there are checkboxes in Form B, the checkbox values of Form B are parsed incorrectly and result in null values and loss of data. That would look like this:
var postData = $(this.form).serializeObject();
var items = $('.item-selector:checked').map(function(){
return this.value;
}).get();
if(items.length > 0) {
postData.itemId = items;
}
Using JSON.stringify revealed the object structure to be like this:
{
"name":"Simon J. Kok",
"address_id":"39669",
"email":"*****",
"content_id":"21921",
"client_id":"42101",
"is_ebill":["","1"], <-- this is a checked checkbox
"is_banned":"", <-- this is an unchecked checkbox
"button":"save"
}
The checkboxes in Form B look like
<input type="checkbox" value="1" name="is_ebill" />
<input type="checkbox" value="1" name="is_banned" />
So what I need is either some insight on how to add the checkboxes from Form A to the $.serializeArray() result array -OR- a way to solve the issue of a checked checkbox returning an array when using Ben Alman's plugin.
Here's one approach. First it requires a hidden field in form-b:
<input type="hidden" id="itemId" name="itemId" value="" />
This would be populated with the item-selector data when the form is submitted:
$('#form-b').on('submit', function() {
var checkedValues = [];
$('.item-selector:checked').each(function() {
checkedValues.push($(this).val());
});
$('#itemId').val(checkedValues.join(','));
console.debug('Form B data:', $('#form-b').serializeArray());
});
Adjust the syntax to suit your idiom. Here's a fiddle to demonstrate:
http://jsfiddle.net/klenwell/12evxfvc/
Actually I kinda answered my own question already when I asked it. I used JSON.Stringify to output the JSON formatted string of what $.serializeArray() returned and it became apparent what the structrure needed to work. So here is how to add array values one by one to an array retrieved using $.serializeArray():
var items = $('.item-selector:checked').map(function(){
return this.value;
}).get();
$.each(items, function(i, v){
postData.push({name: 'itemId[]', value: v});
});
For some reason I have HTML like this -
<input type="text" value="100" name="ProductPrice[1][]">
<input type="text" value="200" name="ProductPrice[2][]">
<input type="text" value="300" name="ProductPrice[3][]">
<input type="text" value="400" name="ProductPrice[4][]">
And process this on server side like this -
foreach ($_POST['ProductPrice'] as $ProductId => $Price)
{
//$Price = Price[0];
}
This works fine for me. However my problem is with validating this on client side with jquery.
I tried $.each($("input[name='ProductPrice[][]']"), function(key, value) {
but nothing seems to be working. How can I read those input boxes using the NAME property.
You can use the "Attribute Starts With Selector":
$("[name^=ProductPrice]").each(function() {
var name = $(this).attr("name");
var value = $(this).val();
// Do stuff
});
It will select all elements whose name starts with "ProductPrice"
hi everyone i have a problem in javascript i can print array if fix them in html but whn i try to print them on clic they are not working just print the array names
if i print seriesre simple it print values that is fine but when i check any checkbox and want to print one or tow of them it just showing array name not values
thanks for help
check this example
$(document).ready(function() {
Comment = [['2011-01-29',7695],['2011-02-02',19805]];
WallPost = [['2011-01-29',11115],['2011-02-02',8680]];
Likes = [['2011-01-29',5405],['2011-02-02',10930]];
var seriesre= [Comment,WallPost,Likes];
var mygraphs = new Array();
alert(seriesre);
$("#testCheck").click(function() {
i=0;
$("#testCheck :checked").each(function() {
mygraphs[i]= $(this).val();
i++;
});
newseriesre = "["+mygraphs+"]";
alert(newseriesre);
});
});
<div class="activity">
<form method="POST" id="testCheck" name="myform">
Likes
<input type="checkbox" value="Likes" name="box2">
Comments
<input type="checkbox" value="Comment" name="box3">
Wall Post
<input type="checkbox" value="WallPost" name="box4">
</form>
</div>
You can use
alert(myarray.join())
to alert your array's values
You should use a associative array instead of an array, so that you can look up the data based on the name as a string instead of trying to find the variable. All objects in Javascript are associative arrays, so just put the data in an object.
Also:
Create the mygraphs array inside the event handler, otherwise it can not shrink when you uncheck options.
Catch the click on the checkboxes inside the form, not on the form itself.
Put a label tag around the checkbox and it's label, that way the label is also clickable.
You don't need an index variable to put values in the mygraphs array, just use the push method to add items to it.
http://jsfiddle.net/cCukJ/
Javascript:
$(function() {
Comment = [['2011-01-29',7695],['2011-02-02',19805]];
WallPost = [['2011-01-29',11115],['2011-02-02',8680]];
Likes = [['2011-01-29',5405],['2011-02-02',10930]];
var seriesre = {
'Comment': Comment,
'WallPost': WallPost,
'Likes': Likes
};
$("#testCheck :checkbox").click(function() {
var mygraphs = [];
$("#testCheck :checked").each(function() {
mygraphs.push(seriesre[$(this).val()]);
});
alert("["+mygraphs+"]");
});
});
HTML:
<div class="activity">
<form method="POST" id="testCheck" name="myform">
<label>
Likes
<input type="checkbox" value="Likes" name="box2">
</label>
<label>
Comments
<input type="checkbox" value="Comment" name="box3">
</label>
<label>
Wall Post
<input type="checkbox" value="WallPost" name="box4">
</label>
</form>
</div>
I understand that you want to alert the selected values when clicking anywhere on the form? If that's true correct code with minimal changes to your existing code will be:
var mygraphs = [];
$("#testCheck").click(function() {
$("#testCheck :checked").each(function() {
mygraphs.push($(this).val());
});
alert("Selected values are: " + mygraphs.join(", "));
});
You can try this.
alert($("#testCheck :checked")
.map( function(i, field) { return field.value}
).get());
Check your working example in http://jsfiddle.net/dharnishr/d37Gn/