Want value from javascript in Jquery, this is php? - javascript

I am following this example - http://jqueryui.com/selectable/#serialize and would like to be able to set the value of a hidden input field based on the user selection. So rather than the value being displayed as per the example, that value instead would be consecutively added to the hidden input field value. How can I achieve this?
<input type="hidden" />

If you want the selected value to be placed in your hidden field, add a class or id to your hidden input, and then change the following lines from the source example page:
your hidden input
<input type="hidden" id="hiddenInput" />
from the example, change
var result = $( "#select-result" ).empty();
to your hidden input
var result = $('#hiddenInput').empty();
then change
result.append( " #" + ( index + 1 ) );
to
result.val('#' + (index + 1));
to add the values rather than replace them, change the line to
result.val(result.val() + "#" + ( index + 1 ) );
here is a working example - http://jsfiddle.net/DBuVf/1

Related

Get Array of Input fields values and append itinto the associated textarea

I have some input field dynamically generated inside form. I am trying to read the value of hidden input and append to to the end of text area
.<input type="hidden" id="formtype_loans_0_comment" name="formtype[loans][0][comment]" disabled="disabled" value="VAlue 1 value 123" />
<textarea id="formtype_loans_0_description" name="formtype[loans][0][description]">Text Area 1 or 1 </textarea>
<input type="hidden" id="formtype_loans_1_comment" name="formtype[loans][1][comment]" disabled="disabled" value="VAlue value 123" />
<textarea id="formtype_loans_1_description" name="formtype[loans][1][description]">test desc</textarea>
and Here is the js code, but it's not working,
var values = [];
$("input[name='formtype[loans][][description]']").each(function() {
values.push($(this).val());
});
alert(values);
Your selector "input[name='formtype[loans][][description]']" won't match any elements, because the [] in the middle will not match to the [0] or [1] (etc.) in the middle of the actual element name attributes.
For the HTML shown you could use the attribute starts with selector [name^=value]:
$('input[name^="formtype[loans]"]').each(function() {
If each textarea will always immediately follow its associated hidden input then within the .each() loop that iterates over the inputs you can say $(this).next() to get the textarea.
If the textareas might be elsewhere in the DOM then you could find them by selecting by the name attribute based on the name of the current input:
$('textarea[name="' + this.name.replace("comment", "description") + '"')
Demonstrated in context:
$('input[name^="formtype[loans]"]').each(function() {
var val = this.value
// add input's value to end of associated textarea's existing value:
$('textarea[name="' + this.name.replace("comment", "description") + '"')
.val(function(i, v) { return v + ' ' + val })
})
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<input type="hidden" id="formtype_loans_0_comment" name="formtype[loans][0][comment]" disabled="disabled" value="Hidden value 0" />
<textarea id="formtype_loans_0_description" name="formtype[loans][0][description]">Text Area A</textarea>
<input type="hidden" id="formtype_loans_1_comment" name="formtype[loans][1][comment]" disabled="disabled" value="Hidden value 1" />
<textarea id="formtype_loans_1_description" name="formtype[loans][1][description]">Text Area B</textarea>
If you want to simply replace the textarea's current value rather than adding to the end of it then you can simplify the above to:
$('input[name^="formtype[loans]"]').each(function() {
$('textarea[name="' + this.name.replace("comment", "description") + '"')
.val(this.value)
})
var values = [],
inputs = $('input[type="hidden"]'),
textareas = $('textarea');
if (inputs.length === textareas.length) {
$.each(inputs, function(i, input) {
var val = ($(input).val()) ? $(input).val(): undefined;
if (val) {
$(textareas).eq(i).empty().val(val);
}
});
}
alert(values);
The working code above assumes a couple of things:
There will always be one textarea per hidden input.
The associated textarea will always be the next sibling after the hidden input.
Even if that is not the case, there are still various ways to resolve this challenge. But I'll break down the different parts of the code:
First, instantiate your variables. Most importantly, cache your selected HTML elements into vars: touching the DOM is expensive and negatively impacts performance (e.g. querying the DOM each time in a loop).
Next, we put a conditional test to ensure there is one textarea for each input. No need to waste time iterating through a loop looking for elements that aren't there.
Finally, iterate through each of the selected inputs confirming each of them have a value. Again, no need manipulating textarea if there is no value to insert. If there is a value in the input, insert it into the textarea that occupies the same position as the input in each of your arrays of elements.

Jquery Incrementing field names

Following on from my previous question
I've now got a form that when clicking add, adds a new input field to the form incrementing the field name and input text by one each time. eg: phone_number1, phone_number2 etc
The jquery I'm using is :
$(document).ready(function(){
var phone_number_form_index=1;
$("#add_phone_number").click(function(){
phone_number_form_index++;
$(this).parent().before($("#phone_number_form").clone().attr("id","phone_number_form" + phone_number_form_index));
$("#phone_number_form" + phone_number_form_index).css("display","inline");
$("#phone_number_form" + phone_number_form_index + " :input").each(function(){
$(this).parent().find('span').text('Phone number ' + phone_number_form_index);
$(this).attr("name",$(this).attr("name") + phone_number_form_index);
$(this).attr("id",$(this).attr("id") + phone_number_form_index);
});
$("#remove_phone_number" + phone_number_form_index).click(function(){
$(this).closest("div").remove();
});
});
});
This JFiddle shows the form working and when adding a new row the field name is incremented as is the input text.
http://jsfiddle.net/yezw6c51/25/
However if I remove a field, the numbering can get messed up.
eg:
With one field the input text and field names are Phone Number 1 /
phone_number1
With two fields the input text and field names are Phone Number 1 &
Phone Number 2 etc
With three fields the input text and field names are Phone Number 1 &
Phone Number 2 & Phone Number 3 etc
if I then remove phone number 2 using the remove button I end up with 1 & 3, clicking add starts at 4.
Is there any way if I delete 2 instead of 1 & 3, I would get 1, 2 and the next add would be 3 ?
This would need to update all field names and input text entries that are being updated.
After adding/removing you can renumber all the inputs and labels like follows:
$(document).ready(function(){
$("#add_phone_number").click(function(){
$(this).parent().before($("#phone_number_form").clone().show());
reNumberInputs();
});
$("form").on("click", "[id^='remove_phone_number']", function(){
$(this).closest("div").remove();
reNumberInputs();
});
});
function reNumberInputs() {
$("input[type='text']:visible").each(function(index, element) {
var displayIndex = (index + 1).toString();
element.id = "phone_number" + displayIndex;
element.name = "phone_number" + displayIndex;
if (index > 0) {
$(this).prev("span").html("Phone number " + displayIndex);
$(this).next("input").prop("id", "remove_phone_number" + displayIndex).prop("name", "remove_phone_number" + displayIndex);
}
});
}
.hidden {
display: none;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<div id="phone_number_form" class="hidden">
<p>
<span>Phone number</span> : <input type="text" name="phone_number" />
<input type="button" id="remove_phone_number" value="Remove" />
</p>
</div>
<form>
<p>
Phone number : <input type="text" name="phone_number1" />
</p>
<p>
<input type="button" value="Add phone number" id="add_phone_number" />
</p>
</form>
Updated Fiddle
You can use the field name as phone_number[] this will be the standard.
If you can't change the procedure then on submit of form rename your fields by getting all the created one by one and assigning current text field values to new fields but it is not a standard method.
Hope you get your answer and if you have any other question get in touch with me on my new blog on http://www.sourabhmodi.in/. I will be happy to help you..

Organizing values of child elements for processing of a draggable form

in my form, the user can click a button to create input fields. Inside each of the created input fields, they can click the "add media links" button to create another input field underneath. They can add as many media links as they please or none at all. The first set of input fields are also sortable. I have the user interface working, I'm just wondering how to go about processing it.
right now, I am basically grabbing all of the values entered from the first set of input fields (aka "thestepvalues" in the code) and then grabbing all of the values entered from the second set of input values (aka "links" in the code) and then URL enconding it and serializing it to send to the my process.php file. The code is below:
$("#new_post").submit(function(e){
e.preventDefault();
//enter each of the values for 'the step' input field into an array
var thestepvalues = $("input[name='thestep\\[\\]']")
.map(function(){return $(this).val();}).get();
//enter each of the values for each 'links' input field into an array
var linkvalues = $("input[name='link\\[\\]']")
.map(function(){return $(this).val();}).get();
//this will basically convert everything entered into the steps as well as the links fields
//into URL appropriate strings to pass on to the process.php file
var i, string="";
for(i=0;i<thestepvalues.length; i++){
string += "thesteps[]=" + encodeURI(thestepvalues[i]) + "&";
}
for(i=0;i<linkvalues.length; i++){
string += "links[]=" + encodeURI(linkvalues[i]) + "&";
}
//send the data from the string (both kinds of input fields) as well as any
//other input fields (that aren't dynamic) from the form
$.post("process.php", string + $("#new_post").serialize(),
function(data){
if(data.email_check == 'invalid'){
$("#message_post").html("<div class='errorMessage'>Sorry " + data.name + ", " + data.email + " is NOT a valid e-mail address. Try again.</div>");
} else {
$("#message_post").html("<div class='successMessage'>" + data.email + " is a valid e-mail address. Thank you, " + data.name + ".</div>");
}
}, "json");
});
For a sample of data entered into the form, how do I go about indicating which link belongs to the parent input field? Baring in mind the parent input fields are sortable jquery ui elements.
here's a sample set of data entered, as you can tell I have no way of knowing which input field the child links belong to:
[thesteps] => Array
(
[0] => This is really the second input field, but dragged up to the first position.
[1] => This is the second input field, but used to be in the first position.
[2] => this is the third input field
)
[links] => Array
(
[0] => this is the first (child) link for the first position.
[1] => this is actually the (child) link for the third field!
)
Any help would be greatly appreciated, thanks in advance
-- 24x7
You could use HTML5 custom data attributes, setting the value of each linked set to be the same number.
For example:
<input id="1" data-newinput-id="1" />
<input id="2" data-newinput-id="1" />
<input id="3" data-newinput-id="2" />
<input id="4" data-newinput-id="2" />
Even if the inputs are re-arranged, you can match them up by getting the attribute values in jQuery like so:
var id = $(this).attr("data-newinput-id"); // 1

Jquery/Javascript get id of a textbox using the id of another textbox

I want to use a jQuery/JavaScript function to validate the input of a textbox.
I have pairs of checkboxes like this:
<input type="text" id="MinMondayTxt" />
<input type="text" id="MondayTxt" />
this is for each day of the week (MinTuesdatTxt, MinWednesdayTxt...)
The Function is like this:
function ValidateTxt(TxtId){
}
It take the Id of a textbox as input. What I want to do is the following:
1) Check if the Id starts with "Min"
2) Get the corresponding textbox, by removing "Min" from the id. for example if we have MinMondayTxt I want to remove the "Min" in order to access the MondayTxt textbox
3) Compare the the values of the 2 textboxes (all values are numeric)
4) if MinMondayTxt > MondayTxt Alert the user
I am looking for help for step 1) and 2) : How can I check if the id starts with "Min" and how to get the corresponding textbox id (by removing the min)
You can use replace() method with the #id selector of jquery as below
function ValidateTxt(TxtId){
var withoutminid = TxtId.replace(/^Min/, '');
var withouminidval = $('#' + withoutminid).val();
var minidval = $('#' + TxtId).val();
}
This will remove "Min" if present, then fetch the jQuery object:
$('#' + TxtId.replace(/^Min/, ''))
maybe you could try with split:
txtId.split('Min');
if Min exist it should create an array like that :
array = ["Min","MondayTxt"];
then you just have to use array[1].

jQuery checkbox selector question

Given some markup where there are a series of inputs (checkboxes) at an arbitrary depth, how can I determine if a given input is checked based on its value:
<ul id="root_node">
...
<li>
...
<span>
<input value="val_1" ... />
...
<input value="val_2" ... />
...
So, what I need is: given root_node and an input value (e.g. val_2), I want to determine if the corresponding checkbox (somewhere underneath root_node) is checked.
You can jQuery selections based on attributes: http://api.jquery.com/attribute-equals-selector and the :checked 'pseudo class'
$('input[value="val_1"]:checked')
so you could do:
if $('input[value="val_1"]:checked').val() !== undefined) {
// do something
}
Hope this help,
Martin
You can do something like:
var context = "root_node";
var value = "val_2";
var checked = $("input:checkbox[value='" + value + "']",
$("#" + context)).attr("checked");
If the context never changes, you can shorten the above into:
var checked = $("#root_node input:checkbox[value='" + value + "']")
.attr("checked");

Categories