jquery, append multiple values to one input hidden - javascript

I have a following variable
var $pk3s_c = $('<input id = query_form_tbl_info_'+query_index +'_pk3ss[] name =query_form[tbl_info]['+query_index+'][pk3ss][] type = hidden></input>');
and an array
var pk3s = opts[tbl]["cols"];
during iteration through the array, I want to append the elements of an array to $pk3s_c
$.each(pk3s, function(i,pk3){
$pk3s_c.attr('value',pk3);
})
the code above is not working, it shows me that I have appended only last element of a pk3s, and not all of them. How can I append each element of p3ks into my hidden input?

You aren't going to get an array into a string field without converting it into a string.
The JSON format is very useful for this
// convert the array to a string
var myString = JSON.stringify(myArray);
// put the string into the field as it's value
$('input').val(myString);
Javascript can interpret the resulting string and server side languages can easily convert it from a string into an array value they can understand (see for php, ruby)
Here is an example in a jsfiddle

For readability, I would pass the arguments as a parameter to the jQuery function
Would look like
var values = ['argument1', 'argument2', 'argument3'];
var query_index = 43;
var jqueryAttributes = {
id: 'query_form_tbl_info_' + query_index + '_pk3ss[]',
name: 'query_form[tbl_info][' + query_index + '][pk3ss][]',
type: 'hidden',
value: JSON.stringify(values)
// if your server don't support HTML encoding, use the one below instead
// value: "['"+values.join("','")+"']"
};
var $newElement = $('<input/>', jqueryAttributes);
alert('you element would look like : ' + $newElement[0].outerHTML);
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.0.0/jquery.min.js"></script>

Related

how to get div attributes into json

I have the following div
<div class="specialbreaek">
This div is stored in a JavaScript variable
I want to convert this into json so that i can get the class name easily
I tried JSON.parse() but still not get the required result
Any Help will be appreciated
Thanks in advance !
I see a few solutions depending on what you mean by "JavaScript variable". If the element is stored as a string, you can use a combinations of String.prototype.search() and String.prototype.substring() to extract the class. For example:
var s = '<div class="specialbreaek">';
var index = s.search(new RegExp(/class=".*"/, 'i'));
s = s.substring(index + 7);
var index = s.search(new RegExp(/"/, 'i'));
s = s.substring(0,index);
document.write(s);
If I understood you correctly, you have a div with several attributes and you want to extract them (using JS) and convert them into a JSON string.
If that's the case, you can use this to extract all attributes and then use any method you want to concatenate them into JSON
$(function() {
var mydiv = $("#mydiv");
var results = "";
// The attributes property contains all attributes of an element
$.each(mydiv.prop('attributes'), function(index, attr) {
// this.attributes is not a plain object, but an array
// of attribute nodes, which contain both the name and value
results += attr.name + ":" + attr.value;
results += ", ";
});
$("#res").text(results);
console.log(results);
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="mydiv" class="myclass" style="mystyle">
my div text
</div>
<hr/>
<h2>results</h2>
<div id="res"></div>
To convert javascript variable into Json is JSON.stringify
Try this
$(function(){
var element = $(".specialbreaek");
var jsonstr = JSON.stringify(element);
console.log(jsonstr);
})
It will output this.
{"0":{},"length":1,"prevObject":{"0":{},"context":{},"length":1},"context":{},"selector":".specialbreaek"}

Inserting a string at a variable index

I have not been able to find a working example or a good explanation of how I can achieve the following: (I would appreciate if anyone can point me in the right direction.
I have a query string: **"/api/bla?sources=[1,2]&plans=[1,2]&codes=[1,2,3]"**
I will be updating the query string via either javascript or jquery when certain events occur on my page, doesnt matter which.
For example, there is a multi select dropdown on the page which houses [sources] and [plans] and [codes]... These dropdowns have IDs which i am to update my request url with upons selecting items in teh dropdowns.
When a source with ID "3" is selected from the dropdown (or checkbox, doesnt matter what page controls are being used) the query string parameter sources[1,2] will need a "3" appended. Likewise then if the item with an ID of "2" is unselected, it will likewise be removed from the query string leaving the new string as sources[1,3]
I am somewhat new to javascript/jquery and especially more advanced string manipulation. I have been attempting to recreate something to demonstrate this and have gotten to the following which is not fully working.
Basically my initial if statement works as intended, but the moment the else is hit (when another ID needs to be added to an existing model in the query string - like a second ID for [sources] or [codes]) it returns wonky output - seeng as I couldnt get the right formula to update everything correctly.
//TIMEMTABLE QUERY
function updateCalendar(filter_id, filter_element) {
//Run through the filter checks before making final call to query and update timetable?
//GET THE MODEL/OBJECT NAME
var queryName = filter_element.attr('data-owner');
//GET THE IDs //this is either an array of all selected IDs or a single id which is used in the else statement
var queryId = filter_element.attr('value');
var queryIds = $('#'+filter_id).val();
var modelCheckIndex = requestString.toLowerCase().indexOf(queryName.toLowerCase());
//build a request string
if (modelCheckIndex < 0) {
console.info('ADD MODEL TO QUERY STRING');
requestString = requestString + "&" + (queryName.toLowerCase() + "[" + queryIds + "]");
console.log(requestString);
}
else{
console.info('UPDATE MODEL ON QUERY STRING');
var position = requestString.toLowerCase().indexOf(queryName.toLowerCase());
//requestString = requestString.substr(modelCheckIndex -1, requestString.length -1) + "," + queryId + "]";
requestString = requestString.slice(modelCheckIndex.indexOf("]"), modelCheckIndex) + "," + queryId;
console.log(requestString);
}
//MAKE THE API CALL USING CREATED QUERY STRING
}
If anyone has any examples or fiddles lying around I would also appreciate it.
Fiddle I am trying to get to work
It looks like you are just having trouble parsing and updating a query string. In which case, I have a function I've been using for that (thank you Google)
function getUriParams(string) {
var params = {},
queryString = string.slice(string.lastIndexOf('?')).substring(1),
regex = /([^&=]+)=([^&]*)/g,
m;
while (m = regex.exec(queryString)) {
params[decodeURIComponent(m[1])] = decodeURIComponent(m[2]);
}
return params;
}
The input is your requestString and the output is an object of key value pairs of the query string.
To make the object a string, jQuery makes it easy with $.param().
//get key value pairs
var obj = getUriParams(requestString);
//make query string
var str = $.param(obj);
I suggest to change the logic a bit. I would use some data storage for the wanted parameter and rebuild the request string every time when it's necessary, like the below example.
It is much more better, than rebuild the string each time when some value has changed.
var data = {
sources: [1, 2],
plans: [],
codes: [1, 3, 4]
};
function buildStr() {
function get(key) { return key + '=' + JSON.stringify(data[key]); }
return '/api/bla?' + ['sources', 'plans', 'codes'].map(get).join('&');
}
document.write('<pre>' + buildStr() + '</pre>');

javascript, selecting one value from object that starts with specific letters

I am selecting all classes from an attribude like so:
var sOption = $(this).attr('class');
in console.log it returns test_1 custom_selectbox
From this i want it to select the class that starts with test_, so with this example it would only return test1. I did the following like so:
var sOption = $.trim($(this).attr('class').replace('custom_selectbox',''));
In this sittuation it returns what i want, but if i add more classes to the attribute where it takes the classes, i would need to also add those class names into replace area:
var sOption = $.trim($(this).attr('class').replace('custom_selectbox','' , 'more_classes', '', 'and_so_on' , ''));
What i want is - instead of using trim and replace , get the test_ classes from the object using regular expressions (bad example):
var sOption = $(this).attr('class'); //get the `test_1 custom_selectbox`
//somehow use the regular expression on this object, so it would select an item from sOption that starts with `test_`
Hopefully i made it understandable what im looking for..
You may split the string into an array, using space as item delimiter, and then filter that array for elements that match your string:
"test_1 custom_selectbox"
.split(' ')
.filter(function(x) { return x.indexOf('test_') == 0; })
You could of course extract that to a plugin:
$.fn.getClasses = function(prefix) {
return $(this).attr('class').split(' ').filter(function(x) { return x.indexOf(prefix) == 0; });
};
Called like so:
$(this).getClasses('test_');

jQuery getting value from dynamic array

I have an array with divs ids (in my case its all divs ID values od parent div (#area) ):
jQuery.fn.getIdArray = function () {
var ret = [];
$('[id]', this).each(function () {
ret.push(this.id);
});
return ret;
};
var array = $("#area").getIdArray();
I need to get an array field value, something like this:
var lef = $("#array".[0]).css("left");
Taking a wild swing at it (see my comment on the question):
var array = $("#area").getIdArray();
var lef=$("#" + array[0]).css("left");
That assumes that getIdArray returns an array of strings, where each string is an id value for a DOM element, and that you want to get the left value for the first of those elements.
So for instance, if the array comes back as:
["foo", "bar", "charlie"]
then the selector created by "#" + array[0] is #foo, so you end up getting the left value for the foo element.
If you have an actual JS array within your variable array just use bracket notation to access each individual ID.
// I have the # before-hand since I'm assuming you have just the ID name
var lef = $('#' + array[0]) // this will access the 1st one in the array
I think you are looking for this :
var divYouWantToChange = $("#"+array[0]);
I try to formulate this as an answer because getIdArray is not a jquery function and we don't know what it does. If you'd like to apply a custom filter to the $("#area") collection you can do so using filter. This will return a jquery object where you can get the .css("left") from.
If you'd like to save both the id's and the left property you can do so with the following code:
var objects=[];
$("#area").filter(function(){
$this=$(this);//cache the object
objects.push({id:$this.attr("id"),
left:$this.css("left")
};
});
console.log(objects);

Get inputs value and separated by "|"

I have inputs and I need to get values and separated by "|" symbol.
My input:
Output what I need:
00:00|00:00|00:00
My code is :
(and it's not working)
var timesArray = $('table').find('input');
var times = timesArray.val();
$('.alltimes').val(times);
Given that .val returns the value of each element (whatever input type it is in your screenshot), then you can use .map: http://jsfiddle.net/RrCYD/.
var values = $("input").map(function() {
return $(this).val(); // map each element to its value
}).get().join("|"); // get real array and join
See comments in code:
// Create an array to store the input values
var inputValues = [];
// Iterate over input's and store their value in the array
$('table').find('input').each(function () {
inputValues.push(this.value);
});
// Create pipe=delimited string from array of values
var delimitedInputValues = inputValues.join("|");
Additional Information
MDN - array.join
jQuery - .each()

Categories

Resources