Clone element and increment index placed in name by 1 - javascript

Lets say I have this input:
name="fecha_inicio[2]"
And I want to clone it and generate:
name="fecha_inicio[3]"
How can I do so?
I tried something like this, but Its ugly and it won't work..
var $input = $original.clone();
var name = $input.attr('name');
name.replace('['+(indice-1)+']', '['+indice+']');
$input.attr('name', name);

replace method doesn't modify string in place, but returns a new string. So your code should be:
name = name.replace('['+(indice-1)+']', '['+indice+']');
Also maybe you don't really need to have such index names. You can simply go with name="fecha_inicio[]" and don't worry about index. Later you would get form data with say serialize method.

Related

Array to Newline String to Array again through HTML

I have an array that comes in from from my API that I would like to arrange in a way that is better for the user (namely, in a column as opposed to the typical comma separated printed array).
This is my JS Fiddle to give a clearer picture: https://jsfiddle.net/2z89owas/
My question is, how can I get output3 to display just like output (and maintain its status as an iterable array like it was as dates)?
First you should not be using value for an html element. You can use .value for extracting value from inputs. Change your line to:
var val = document.getElementById('output2').innerHTML;
Afterwards, you have to split the same way you did join.
var dates3 = val.split('<br>');
document.getElementById('output3').innerHTML = dates3;
You can directly use join, something like:
document.getElementById('output3').innerHTML = dates.join(',');
You can try mapping over the contents of dates instead, as so:
let datesElem = dates.map(date =>`<p>${date}</p>`);
// test: console.log(datesElem)
document.getElementById('output3').innerHTML = datesElem

Get how many instances of a 'field' are in a text, and append each value with the same 'field' to the same variable

So lets say I have a mailto email in which a checkbox question exists that asks the user to pick the best fruits out of a list of fruits (check all that apply.) They end up with apples, bananas, and pears. The mailto email that they trigger then contains the following (assuming the checkboxes in the question are named bestFruits):
...
bestFruits=apples
bestFruits=bananas
bestFruits=pears
...
So in my javascript file, I have the following line to parse values from the email:
var bestFruits = mail.bodyText.match(/bestFruits=\s*(\S.*\S)\s*/);
So my issue is that this would (presumably) take only one value by the end. What I need, is for the javascript to loop and add each value of bestFruits in the email to the bestFruits var so that each value (apples, bananas, and pears) are all in the bestFruits var.
Is there any way to do this? I tried making a for loop, but I couldn't determine the syntax to loop through the mailto email body and add each instance of bestFruits to the variable.
I'm still extremely new to all this, as I was thrust in recently. If I'm missing something fundamental, I'd appreciate a quick pointing-out. If you require any more info, I'd be happy to try to provide it.
Thanks for reading guys!
You don't need looping. You do need to match all the fruits (as per your example, matching all single words after bestFruits), remove bestFruits= from the matches, join the resulting array and store it in a variable. Like this:
var bestFruits = mail.bodyText.match(/bestFruits=\w+/g)
.map(function(x){return x.split('=')[1]})
.join(',');
What does it do:
Matches all your best fruits.
Takes each bestFruits=abc element and replaces it with abc (i.e., splits with = separator and takes the second part)
Makes the string of your fruits (converts the resulting array to string with , joiner).
You were very close - modified your regex a little bit:
var body = `this=is
an=example
bestFruits=apples
bestFruits=bananas
bestFruits=pears
of=doing
things=ok?
`;
var re = /bestFruits=(.*)/g;
var fruitMatches = body.match(re);
var bestFruits = fruitMatches.map(function(fruitMatch) {
return fruitMatch.split('=')[1];
});
console.log(bestFruits); // ["apples", "bananas", "pears"]
Fiddle

Extract value between HTML tags from JSON

I got some problem. I tried to know how to do but... nothing... Im doing something wrong and i dont know what...
I have a ajax request to JSON.
I receive some properties with the values. One of them is with HTML inside:
"<p>Title</p>
<p>Category</p>
<p>First p.</p>
<p>Second p.</p>"
I would like to get the "Title" in another variable and the "Category" in another variable. The "first p" and the "second p" in another variable.
I did something like this, but nothing happen.
tTitle = $(textThumb).find("p:nth-child(0)").html();
tCat = $(textThumb).find("p:nth-child(1)").html();
tText = $(textThumb).remove("p:nth-child(0)","p:nth-child(1)").html();
All of them became undefined.
If I print textThumb and the other values from other parameters are also ok, is just here the problem that i dont know how to think about it
Thanks,.
Try something like this:
var $p = $(textThumb).filter("p"),
tTitle = $p.eq(0).text(),
tCat = $p.eq(1).text();
The main thing is to use .filter() rather than .find() because the latter looks for elements that are descendants but the elements you want are at the top level.
"The "first p" and the "second p" in another variable."
If you mean that you want the text from both of those paragraphs into the same variable then perhaps:
var tText = $p.slice(2).text();
Demo: http://jsfiddle.net/g39Gm/
var tree = $(textThumb);
tTitle = tree[0].innerText;
tCat = tree[1].innerText;
tText = tree[2].innerText + tree[3].innerText
There are probably better ways to go about whatever you are doing besides returning JSON with html as values - that said, what you need to do is put a string with one parent node into the jQuery selector.
$('<div><p>Hi</p><p>Hi Again</p></div>').find('p').eq(0).text() // 'Hi!'
or with nth-child() selector (which should start at 1)
$('<div><p>Hi</p><p>Hi Again</p></div>').find('p:nth-child(1)').text() // 'Hi!'
In your case $('<div>'+textThumb+'</div>') ...

Get the length of an array using document.getElementsbyName()

Hi I have an array like this.
var i;
for(i=0;i<10;i++){
$('<input/>').attr('type','text')
.attr('name','TxtBx_[]')
.attr('id','TxtBx_' + i)
.attr("readonly","readonly")
.attr('value',i)
.addClass('txtbx')
.appendTo($div);
}
And I prints the 10 input boxes well.
Later I need to get the number of text boxes I have created. So I'm using
var myarr=document.getElementsByName('TxtBx_');
var numberofElements=myarr.length;
but when I put an alert to check the value of numberofElements it gives me always 0. The length of the array must be 10. Could someone please let me know the mistake I have made.
The elements' names are TextBx[], not TxtBx_.
var myarr=document.getElementsByName('TextBx[]');
var numberofElements=myarr.length;
Element names are TextBx[] and TxtBx_ is a class name
var myarr=document.getElementsByName('TextBx[]');
var numberofElements=myarr.length;
Read getElementsByName() documentation for more information
var numberofElements = document.getElementsByName("TextBx[]").length;
Name of textbox is 'name','TxtBx_[]' getting by TxtBx_.
Because no element has name TxtBx_ . It's TextBx[] actually.
Since you are alrady using jQuery, you can find by class like below,
$('.txtbx').length
Few other things, I would like to add here.
attr accepts a object too. So, you can pass all inputs at once. Also, you can pass attributes as second arguement while dynamically creating input. Also, according to jQuery docs, you should specify type in input type while dynamically creating them or it won't work in some IE.
So, try something like this,
var i;
for(i=0;i<10;i++) {
$('<input type="text"/>',{
'name': 'TxtBx_[]',
'id': 'TxtBx_' + i,
'readonly':'readonly'
'value': i,
'class': 'txtbx'
}).appendTo($div);
}
Try it
$("input.txtbx").length;
Just use the class to get them:
var numberofElements = $('.txtbx').length;

Trying to reduce repetition of javascript using a variable

I am trying to reduce the repetition in my code but not having any luck. I reduced the code down to its simplest functionality to try and get it to work.
The idea is to take the last two letters of an id name, as those letters are the same as a previously declared variable and use it to refer to the old variable.
I used the alert to test whether I was getting the right output and the alert window pops up saying "E1". So I am not really sure why it wont work when I try and use it.
E1 = new Audio('audio/E1.ogg');
$('#noteE1').click(function() {
var fileName = this.id.slice(4);
//alert(fileName); used to test output
fileName.play();
$('#note' + fileName).addClass('active');
});
The code block works when I use the original variable E1 instead of fileName. I want to use fileName because I am hoping to have this function work for multiple elements on click, instead of having it repeated for each element.
How can I make this work? What am I missing?
Thanks.
fileName is still a string. JavaScript does not know that you want to use the variable with the same name. You are calling the play() method on a string, which of course does not exist (hence you get an error).
Suggestion:
Store your objects in a table:
var files = {
E1: new Audio('audio/E1.ogg')
};
$('#noteE1').click(function() {
var fileName = this.id.slice(4);
//alert(fileName); used to test output
files[fileName].play();
$('#note' + fileName).addClass('active');
});
Another suggestion:
Instead of using the ID to hold information about the file, consider using HTML5 data attributes:
<div id="#note" data-filename="E1">Something</div>
Then you can get the name with:
var filename = $('#note').data('filename');
This makes your code more flexible. You are not dependent on giving the elements an ID in a specific format.

Categories