How to get the ID of a dynamic element when loaded? - javascript

VIEW
$1 = array('value'=>'1|3','class'=>'temp_stok', 'id'=>'st1');
$2 = array('value'=>'2','class'=>'temp_stok','id'=>'st2');
$3 = array('value'=>'5|7','class'=>'temp_stok','id'=>'st3');
echo form_input($1);echo form_input($2); echo form_input($3);
i want to split every value content '|'
var id = $('.temp_stok').id();
var val_id = $('#st'+id).val();
if(val_id.indexOf('|') >= 1)
{ var _stok = val_id.split('|');
var stok1 = _stok[0]; var stok1 = _stok[1]; }
but the problem is get the id. How can i get id ?

You may try something like this (Example):
// Select all inputs that contains | in it's value
var inputsWithPipe = $("input[value*='|']");
// Then loop all the inputs and split
$.each(inputsWithPipe, function(k, v){
var arr = v.value.split('|');
console.log(arr); // an array of numbers
});
Now you may use each arr array as you want.

Try this to get the id of the element you are interested in:
var id = $('.temp_stok').attr('id');

Related

Naming an element inside javascript

I want the select name array keys have a quotations inside. But this one doesn't generate quotations inside the brackets. How can I achieve it?
var id = "test";
var element = "<select name = 'unit_id["+id+"]' class = 'form-control'></select>";
You can use Template literals which is more cleaner. This does not require string concatenation and character escaping:
var id = "test";
var element = `<select name = 'unit_id["${id}"]' class = 'form-control'></select>`;
console.log(element)
Like this:
var id = "test";
var elemnt = "<select name=\"unit_id['" + id + "']\" class=\"form-control\"></select>";

how to remove particular substring from string using id of li in jquery

I have string
0=>zxz##5=>zxzx##5=>zxz##10=>zxz##1=>asdasd##12=>asdsad##10=>asdsad
where 0,5,10 are ids, text are values and ## is delimiter.
I have id and i want to remove id's value
This is my following code, Please check and suggest.
code1
function remove_feature(id)
{
var feature_str = $("#features_post").val();
var feature_string = feature_str.replace(['id=feature_str'],'', 'gi');
window.jQuery("#features_post").val(feature_string);
window.jQuery("#"+id+"").remove();
alert(feature_string);
return true;
}
code2
function remove_feature(id)
{
var feature_str = $("#features_post").val();
var feature_string = feature_str.replace(id,'', 'gi');
window.jQuery("#features_post").val(feature_string);
window.jQuery("#"+id+"").remove();
alert(feature_string);
return true;
}
I have tried both of code but not working
Try this one with jquery : http://jsfiddle.net/h0qtxn7d/
Can also remove same multiple ids.
var k = "0=>zxz##5=>zxzx##5=>zxz##10=>zxz##1=>asdasd##12=>asdsad##10=>asdsad";
var obj = k.split("##");
var removeItem = 5;
alert('Array before removing the element = ' + obj)
obj = jQuery.grep(obj, function(value) {
return value.split('=>')[0] != removeItem;
});
alert('Array after removing the element = ' + obj);
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
Misread the question, sorry.
To replace each key => value pair within that string you could use regular expressions:
var string = "0=>zxz##5=>zxzx##5=>zxz##10=>zxz##1=>asdasd##12=>asdsad##10=>asdsad";
function remove_feature(id) {
var x = new RegExp("" + id + "\=>[a-z0-9]+(##)?", "gi")
return string.replace(x, "");
}
So, remove_feature(5) prints "0=>zxz######10=>zxz##1=>asdasd##12=>asdsad##10=>asdsad".
If the id parameter is a key which exists in your provided string and the respective name should be returned you could make use of the JSON.parse function pretending to parse a url. Therefore you could replace the delimiters by &s and the => by =s:
var string = "foo=>bar##john=>doe";
function remove_feature(id) {
// id should be something left hand side the =>, like 0 or 1
var _string = string.replace('##', '&').replace('=>', '='),
obj = JSON.parse('{"' + decodeURI(_string).replace(/"/g, '\\"').replace(/&/g, '","').replace(/=/g,'":"') + '"}'),
_id = obj["" + id];
$('#' + _id).remove();
}
Usage: remove_feature("foo") would remove an element with id #bar.

Javascript: How to re-arrange content display of text field?

I have a text field (not a date field) who contain simply a value such "2013-08-27" and my goal would be to reverse the order and get "27-08-2013". So is matter to re-arrange the content but I don't have enough javascript knowledge. I tried using some "date" variable but without success much probably because my field is not a date field.
The html related to the field look like this:
<input type="text" value="2013-08-27" name="my_field" id="my-field" readonly="">
If you can give me an example of code based of this:
var my_field = document.getElementById('my_field');
thank
PS: I precise I don't have access to html of this field because is located to a remote server. I can only interact by adding code in a JS file planned for that. The field have also a "readonly" property because is not planned for be modified.
This code should do the trick:
var revert = function(str) {
var parts = str.split("-");
var newArr = [];
for(var i=parts.length-1; p=parts[i]; i--) {
newArr.push(p);
}
return newArr.join("-");
}
var replaceValueInInputField = function(id) {
var field = document.getElementById(id);
field.value = revert(field.value);
}
var replaceValueInDomNode = function(id) {
var el = document.getElementById(id);
var value = el.innerHTML, newValue = '';
var matches = value.match(/(\d{4})-(\d{2})\-(\d{2})/g);
for(var i=0; m=matches[i]; i++) {
value = value.replace(m, revert(m));
}
el.innerHTML = value;
}
replaceValueInInputField("my-field");
replaceValueInDomNode("my-field2");
jsfiddle http://jsfiddle.net/qtDjF/2/
split('-') will return an array of number strings
reverse() will order array backwards
join("-") will join array back with '-' symbol
var my_field_value = document.getElementById('my_field').value;
my_field_value.split('-').reverse().join("-");
You can use the split function.
var my_field = document.getElementById('my_field').split("-");
the var my_field will be an array of string like : "YYYY,mm,dd"
and then you can re-arrange it in the order you want.
Try this
var date = document.getElementById("my-field").value;
//alert(date);
var sp = date.split("-");
alert(sp[2]+"-"+sp[1]+"-"+sp[0]);
With Jquery
var parts =$('#my-field').val().split("-");
$('#my-field').val(parts[2]+"-"+parts[1]+"-"+parts[0]);
Simple regex:
var res;
test.replace(/(\d\d\d\d)-(\d\d)-(\d\d)/,function(all,a,b,c){res=c+"-"+b+"-"+a;});
JSFiddle: http://jsfiddle.net/dzdA7/8/
You could try splitting the string into array and inverting it's items in a loop:
var my_field = document.getElementById('my_field').value.split("-"),
length = my_field.length,
date = [];
for(i = length - 1; i >= 0; i--){
date.push(my_field[i]);
}
console.log(date.toString().replace(/,/g,"-"));

how to loop though div and get each value

I am trying to figure out how to get each value within my div. I am using
var cart = $('.basic-cart-cart-node-title.cell').text();
It is giving the results of OI-01OP-01OS-10-5SOR-04OR-05
I need to view them one by one: OI-01, OP-01, OS-10-5S, OR-04 OR-05.
So that I can match them against another field.
If you care to help me further, I have another div on the page:
var ParNum = $('.assess-title').text();
I would like to compare the values returned from the var cart and see if that value is in the ParNum. If it is there, I would like to apply a class.
Any help would be greatly appreciated.
Thanks!
You can store the values in an array using .map() method:
var values = $('.basic-cart-cart-node-title.cell').map(function() {
return $.trim( $(this).text() );
}).get();
For checking existence of the ParNum value in the array:
var does_exist = values.indexOf(ParNum) > -1;
Try this to iterate over elements:
var text = '';
$('.basic-cart-cart-node-title.cell').each(function (i, div) {
text += ' ' + $(div).text();
});
or this to get an array of matching div elements:
var divs = $('.basic-cart-cart-node-title.cell').toArray();
for (var i = 0; i < divs.length; i++) {
// $(div).text();
}
Reason for this is that $('.basic-cart-cart-node-title.cell') returns all div's at once, and you need to loop through the result. More specifically, $(selector) returns a so-called "wrapped set". It can be used to access each matching element (as I've shown above) or it can be used to apply any other jQuery function to the whole set at once. More info here.
var text = "";
$('.basic-cart-cart-node-title.cell').each(function(){
text += $(this).text() + ", ";
});
// remove the last ", " from string
text = text.substr(0, text.length -2);
var cart = [];
$('.basic-cart-cart-node-title.cell').each(function {
cart.push($(this).text());
}
This performs the matching and class adding you mentioned in the question.
var ParNum = $('.assess-title').text();
$('basic-cart-cart-node-title.cell').each(function () {
if ($(this).text() == ParNum) {
$(this).addClass("someclass");
}
}
You should try using
var cart ='';
$('.basic-cart-cart-node-title'.find('.cell').each(function()
{
cart = cart + $(this).val();
});
Hope it works for you.
var cart = $('.basic-cart-cart-node-title.cell').text().match(/.{5}/g);
This will give you an array with items 5 chars long. Regexes arent very fast, but a loop might be slower
Or easier to read, and in a string with commas:
var cart = $('.basic-cart-cart-node-title.cell').text(); // get text
cart = cart.match(/.{1,5}/g); // split into 5 char long pieces
cart = cart.join(",",); join on comma

Getting Attributes from User submitted text! RegExp?

I am trying to pull the attributes out of piece of submitted text in Javascript and change it to an array.
So the user submits this:
<iframe src="http://www.stackoverflow.com/" width="123" height="123" frameborder="1"></iframe>
and I would get:
arr['src'] = http://www.stackoverflow.com/
arr['width'] = 123
arr['height'] = 123
arr['frameborder'] = 1
Just need a regexp I think but any help would be great!
I recommend to use a RegExp to parse user-inputed HTML, instead of creating a DOM object, because it's not desired to load external content (iframe, script, link, style, object, ...) when performing a "simple" task such as getting attribute values of a HTML string.
Using similar (although similarcontradiction?) methods as in my previous answer, I've created a function to match quoted attribute values. Both quoted, as non-quoted attributes are matched.
The code currently returns an object with attributes from the first tag, but it's easily extensible to retrieve all HTML elements (see bottom of answer).
Fiddle: http://jsfiddle.net/BP4nF/1/
// Example:
var htmlString = '<iframe src="http://www.stackoverflow.com/" width="123" height="123" frameborder="1" non-quoted=test></iframe>';
var arr = parseHTMLTag(htmlString);
//arr is the desired object. An easy method to verify:
alert(JSON.stringify(arr));
function parseHTMLTag(htmlString){
var tagPattern = /<[a-z]\S*(?:[^<>"']*(?:"[^"]*"|'[^']*'))*?[^<>]*(?:>|(?=<))/i;
var attPattern = /([-a-z0-9:._]+)\s*=(?:\s*(["'])((?:[^"']+|(?!\2).)*)\2|([^><\s]+))/ig;
// 1 = attribute, 2 = quote, 3 = value, 4=non-quoted value (either 3 or 4)
var tag = htmlString.match(tagPattern);
var attributes = {};
if(tag){ //If there's a tag match
tag = tag[0]; //Match the whole tag
var match;
while((match = attPattern.exec(tag)) !== null){
//match[1] = attribute, match[3] = value, match[4] = non-quoted value
attributes[match[1]] = match[3] || match[4];
}
}
return attributes;
}
The output of the example is equivalent to:
var arr = {
"src": "http://www.stackoverflow.com/",
"width": "123",
"height": "123",
"frameborder": "1",
"non-quoted": "test"
};
Extra: Modifying the function to get multiple matches (only showing code to update)
function parseHTMLTags(htmlString){
var tagPattern = /<([a-z]\S*)(?:[^<>"']*(?:"[^"]*"|'[^']*'))*?[^<>]*(?:>|(?=<))/ig;
// 1 = tag name
var attPattern = /([-a-z0-9:._]+)\s*=(?:\s*(["'])((?:[^"']+|(?!\2).)*)\2|([^><\s]+))/ig;
// 1 = attribute, 2 = quote, 3 = value, 4=non-quoted value (either 3 or 4)
var htmlObject = [];
var tag, match, attributes;
while(tag = tagPattern.exec(htmlString)){
attributes = {};
while(match = attPattern.exec(tag)){
attributes[match[1]] = match[3] || match[4];
}
htmlObject.push({
tagName: tag[1],
attributes: attributes
});
}
return htmlObject; //Array of all HTML elements
}
Assuming you're doing this client side, you're better off not using RegExp, but using the DOM:
var tmp = document.createElement("div");
tmp.innerHTML = userStr;
tmp = tmp.firstChild;
console.log(tmp.src);
console.log(tmp.width);
console.log(tmp.height);
console.log(tmp.frameBorder);
Just make sure you don't add the created element to the document without sanitizing it first. You might also need to loop over the created nodes until you get to an element node.
Assuming they will always enter an HTML element you could parse it and read the elements from the DOM, like so (untested):
var getAttributes = function(str) {
var a={}, div=document.createElement("div");
div.innerHTML = str;
var attrs=div.firstChild.attributes, len=attrs.length, i;
for (i=0; i<len; i++) {
a[attrs[i].nodeName] = attrs[i].nodeValue];
}
return a;
};
var x = getAttributes(inputStr);
x; // => {width:'123', height:123, src:'http://...', ...}
Instead of regexp, use pure JavaScript:
Grab iframe element:
var iframe = document.getElementsByTagName('iframe')[0];
and then access its properties using:
var arr = {
src : iframe.src,
width : iframe.width,
height : iframe.height,
frameborder : iframe.frameborder
};
I would personally do this with jQuery, if possible. With it, you can create a DOM element without actually injecting it into your page and creating a potential security hazard.
var userTxt = '<iframe src="http://www.stackoverflow.com/" width="123" height="123" frameborder="1"></iframe>';
var userInput = $(userTxt);
console.log(userInput.attr('src'));
console.log(userInput.attr('width'));
console.log(userInput.attr('height'));
console.log(userInput.attr('frameborder'));

Categories

Resources