Concatenate values from script-created list into one field - php

How do I concatenate data from text fields in a script-created list, where the text field names will always be the same as each other? Allow me to explain:
I have a series of points that get added to a list that is create using javascript. This is the script to create the list:
var src = this.parentNode;
var field = $('<input type="text" id="savedpoints" name="savedpoints">').attr({'value': $(src).data('dbId')});
var but = $('<button>').append(' Remove ');
var newItem = $('<li>').append(field).append($(src).data('marker').title);
newItem.append(' ').append(but);
$(but).click(poi.removeItem);
$(poi.saveList).append(newItem);
So, there are items getting added to a list with a button next to them to remove them from the list if they are no longer needed. This list works perfectly.
What I need is to add the values to a text field at the bottom of the form (say, name="allpoints") that concatenates the field values from this list (the text field labelled "savedpoints", with the attribute 'dbId') into a string (e.g. "6, 7, 10, 13, 14,..." etc) whenever an item is removed from or added to the list. I can't work out how this might work!
Any help?

I would add an event handler to a common-ancestor of the remove button(s) and add button(s), which completely rebuilds the contents of "allpoints" when triggered:
$(commonParent).on('click', 'button.remove, button.add', function () {
$('[name="allpoints"]').val($('[name="savedpoints"]').map(function () {
return $(this).val();
}).join(", "));
});
... if you wanted to, you could only add/remove the relevant element to/from the list, but you get the gist.
Note you'll need to add a class to your remove <button> (I've called it remove) in my example, and to your "Add" button.

Related

jquery pull textarea values based on which checkboxes were checked

I'm working on a project that involves returning the id of the checkboxes chosen as well as the text in the corresponding textarea fields for those chosen checkboxes. The data is dynamically displayed and so far my jquery pull of both the checkboxes and textareas work:
var noteList = $("textarea[name='revokeNotes']").map(function(){
return this.value;
}).get().join();
var revokeList = $("input[name='revoke']:checked").map(function(){
return this.id;
}).get().join();
but I'm getting back all of the notes fields and I'm uncertain how to best iterate through them to find the proper notes as their ids aren't sequential but rather based on their id in the table they are being pulled from. The last version of the display code is below:
<td><textarea name=\"revokeNotes\" id=\"".$v["id"]."\" cols=\"30\"rows=\"3\">".$v["notes"]."</textarea></td>
<td><input type=\"checkbox\" id=\"".$v["id"]."\" name=\"revoke\" value=\"".$v["id"]."\" /></td>
Is there a way to reach my goal from this state or should I be using another jquery function, similar to .map()? I thought about using the id field from the checkboxes to iterate through the selected notes and pushing them into an array but I'm not sure 1) if that will work and 2) how to do that.
I need the data back in some form either an array or something I can explode on in php to create an array as I'm passing one value in ajax as there is no set maximum or minimum number of rows that will be displayed per user. Map was working until I threw some commas at it. Extra points for that.
var noteList = $.map(
$("textarea[name='revokeNotes']").filter(function() {
return $(this).closest('td')
.next('td')
.find('input[type="checkbox"]')
.is(':checked');
}), function(el) {
return el.value;
}).join();
adeneo's answer is great, I'd just propose the following improvements:
If possible use class selectors (like '.revoke-notes-area') since those are faster than DOM + attr selectors
Assuming this is a table and there is one textarea checkbox combo per row, you can traverse the tree to the closest <tr> a decouple the JS from depending that the checkbox comes after the text area in the DOM.
var filterMethod = function() {
$(this).closest('tr').find('.revoke-checkbox').is(':checked');
};
var mapMethod = function(el) {
return el.value;
};
var nodeList = $.map($('.revoke-notes-area').filter(filterMethod), mapMethod);
There's no reason you cannot or should not put the filter and map methods inline, I just split them out into variables so it's easier to read here.
You can check out my codepen here: http://codepen.io/aaron/pen/eIpby.

Dynamically changing photo with dropdown

I am new to PHP and am trying to figure out how to code some specific functionality. I have a product page that shows a photo and has two dropdown menus, one for size and one for color. What I would like to do is when the page first loads I set a variable that has the default product SKU. When the menus change I want to change the variable to the combined values of the two menu items selected. As the variable changes I want to reflect this in the photo and in a hidden form value (for eventual submission to a cart).
So when the page loads it shows picture A with the associated values in the size and color dropdowns. Then when either of the dropdowns change the photo dynamically changes to reflect it (while also updating the hidden form value).
Any suggestions would be much appreciated.
JavaScript, or a JS library like jQuery, is what you need here.
For jQuery (preferred, way easier):
var $select = $('#Dropdown'),
$img = $('#Picture');
$select.on('change',function(){
$img.attr('src',$(this).val());
});
For JavaScript:
var dropdown = document.getElementById('Dropdown'),
img = document.getElementById('Picture');
dropdown.addEventListenter('change',function(){
img.src = this.value;
});
Not tested, but should work.
Edit: when using the JavaScript solution, make sure the window is loaded first (it won't work if the elements dont exist yet).
window.onload = function(){
// do your magic here
}
Firstly, PHP is a server side language which effectively means, anything that it generates must be processed by the server and then sent back to the browser. Therefore in this particular case, you need to use a client side language such as Javascript, or to make the code easier, a library such as jQuery.
To learn more about jQuery, see here:
http://jquery.com/
In very generalised terms (as you have not posted any code), here is an example of changing
an image using jQuery:
// Select the dropdown from the DOM
var dropdown = $('#dropdown_id');
// Select the image from the DOM
var image = $('#image');
// Set the onchange event
// This will be fired when the select value is changed
dropdown.on('change',function(){
// Get the value of the selected option
var value = $(this).val();
// Change the source of the image
image.attr('src',value);
});

How to load second DropDown list from Database after first DropDownList is changed

I am building a Web App.
At some point a user needs to input data to a form.
This form has several text fields and DropDownLists.
One of the DDLs is dependent on its previous DDL.
What happens is that when the user selects a value from the first DDL, the second DDL should load data from the database that are related to the selected value of the first DDL.
Up to this point I've implemented only PHP and JS, ( no AJAX, jQuery or anything else ) for handling most of my problems.
I'd like to know how to populate the 2nd DDL from the database after an item on the first DDL was selected.
Any help would be appreciated. Thank you!
Here's an example:
http://tutorialzine.com/2011/11/chained-ajax-selects-jquery/
Google is your friend :)
Ajax is your best bet.
this will help
If the data in the second drop-down is dependent on the data in the first, then you will have to load the values of the second dropdown into a javascript object, like so:
// Given the options in the first dropdown are: "foo", "bar", and "baz"
var secondData = {
foo: ['lorem', 'ipsum'],
bar: [1,2,3],
baz: []
}
Add a 'change' event to the first dropdown, and given the value of that dropdown, load the contents of the second dropdown with the values contained in the secondData object.
If you're comfortable using jQuery (which I would highly recommend), something like this should do:
$("#dropdown").on("change", function() {//change [dropdown] to the actual ID of your dropdown
var selected=$(this).find("option:selected").val();//assuming your dropdown has a value to send, otherwise use text()
$.get("options.php?selected="+selected, function(data) {
var options=data.split("\n");
var newSelectHTML="<select name=\"whatever\">\n";
for (var i=0;i<options.length;i++) {
newSelectHTML+="<option>"+options[i]+"</option>";
}
newSelectHTML+="</select>";
$("#form").append(newSelectHTML);//again, change [form] to the correct ID.
}
}
This code simply gets the value of the currently selected option of the DDL with the ID "dropdown" (change as necessary) and sends it to PHP file options.php in $_GET["selected"];. Assuming that file then outputs a list of options separated by a new line (\n). The JavaScript then takes that, splits it by line, loops through the options, and creates the HTML for a new DDL and appends that to element ID form. No error handling is there, but that, as they say, is an exercise for the reader. Whatever is returned is in the variable data.

jQuery Table AddRow Plugin adding ID numbers to added rows

I have a form and I'm using the jQuery Table AddRow plugin to dynamically add rows to a table, the problem is I'm trying to when you select a Menu Item that the menu item goes into the text box to the left of it. It works on the first row but I can't figure out how to get it to work with rows that are added via the plugin.
You can see my code in action here: http://jsfiddle.net/VXNzd/
Here is the jQuery code:
// This moves the select box text to the input box
$('#mnu_names').change(function() {
var mnuProduct = $("#mnu_names").find(':selected').text();
var mnuCleanProduct = mnuProduct.split(' - ');
$('#topping_name').attr('value', mnuCleanProduct[0]);
});
// This code is needed to add and delete rows with the plugin
$(".toppings_add").btnAddRow({
It may be easier to see what I'm talking about by visiting the jsfiddle link up top. When it loads use the select box to and select something, It will put that info over into the text box without the price info. Add a new row and try it again. Won't work, can't figure out how to make it work.
The problem was as said by tomhallam your ID's are not unique. Also $.change() does not work on blocks added after you ran that. You should instead use $.on('change',...).
I updated your code and posted it on http://jsfiddle.net/PDPbn/5/.
The modified jquery-code goes as follows:
$(document).on('change','.mnu_names',function() {
var mnuProduct = $(this).find(':selected').text();
var mnuCleanProduct = mnuProduct.split(' - ');
$(this).parentsUntil('tbody').find('.topping_name').attr('value', mnuCleanProduct[0]);
});

linked comboboxes in html

Basically my webpage has two comboboxes. First combo box is populated with data comming from MySql. There is a button Add to the side of combo box and when user selectes a item in combo box 1 , clicks on the Add button, that item should get added to the second combo box that is in the same page. Can anyone please tell me how to do this in javascript? or anything?
By the way my web pages are PHP pages.
Thanks.
Hey. You could use a Javascript function like this:
function moveSelectedOption() {
// Fetch references to the <select> elements.
var origin = document.getElementById('origin_select');
var target = document.getElementById('target_select');
// Fetch the selected option and clone it.
var option = origin.options[origin.selectedIndex];
var copy = option.cloneNode(true);
// Add the clone to the target element.
target.add(copy, null);
}
Then you just add a call to it to the button's onclick event.
<button onclick="moveSelectedOption()">Add</button>
If you want to move it rather than copy it, remove the cloneNode line and just add the original option.

Categories