Combining arrays from different inputs - javascript

I'm trying to combine mulitple inputs then combine them to form a sentence/phrase. This example will elaborate it more.
INPUT1: Happy
INPUT2: Birthday to you
INPUT4: You belong to the zoo
INPUT5: and the monkey and the donkey
INPUT6: The Gorilla is you
Output:
Happy, Birthday to you, You belong to the zoo, and the monkey and the donkey, The Gorilla is you
Expected Output:
Happy Birthday to you, You belong to the zoo, and the monkey and the donkey, The Gorilla is you
I want to set a condition where in INPUT one will not be joined using comma(,) rather just a space. How can I accomplish this? Here's a fiddle and code. Appreciate all the help thnx
Fiddle: http://jsfiddle.net/hztMj/6/
Code:
<input class="combine" id="input1" disabled="true" value="Happy"></input>
<input class="combine" id="input2" disabled="true" value="Birthday to you"></input>
<input class="combine" id="input3" disabled="true" value="You belong to the zoo"></input>
<input class="combine" id="input4" disabled="true" value="and the monkey and the donkey"></input>
<input class="combine" id="input5" disabled="true" value="The Gorilla is you"></input>
<input class="combine" id="Voltes5" disabled="true" size="75"></input>
<button id="LaserSword">Set</button>
JS
$(document).ready(function () {
$('#LaserSword').on('click', function () {
var form = $('.combine').not('#Voltes5');
var val = form.map(function () {
var value = $.trim(this.value)
return value ? value : undefined;
}).get();
$('#Voltes5').val(val.join(', '))//part to be improved
});
});

If this a simple-not-dynamic scenario, you can achive that with a simple .slice()
$('#Voltes5').val(val[0] + ' ' + val.slice(1).join(', '))

You can build your sentence this way :
$(document).ready(function () {
$('#LaserSword').on('click', function () {
var form = $('.combine').not('#Voltes5');
var val = "" ;
form.each(function (i,e) {
var value = $.trim(this.value) ;
if(i > 0){ // we don't add a separator for the first element
val = val + ( i==1 ? " " : ", " ) ;
// separator according to index
// (you can easily extend it as you want)
}
val = val + (value || "") ;
});
$('#Voltes5').val(val)
});
});
Demo : http://jsfiddle.net/XF7K8/1/

You can use something like this :
$(document).ready(function () {
$('#LaserSword').on('click', function () {
var form = $('.combine').not('#input1','#Voltes5');
var val = form.map(function () {
var value = $.trim(this.value)
return value ? value : undefined;
}).get();
$('#Voltes5').val($('#input1').val()+" "+val.join(', '))
});
});
DEMO
UPDATE:
In more general ,
$(document).ready(function () {
$('#LaserSword').on('click', function () {
var form = $('.combine').not('.spaceNeeded','#Voltes5');
var val = form.map(function () {
var value = $.trim(this.value)
return value ? value : undefined;
}).get();
var spaceval = $('.spaceNeeded').map(function () {
var value = $.trim(this.value)
return value ? value : undefined;
}).get();
$('#Voltes5').val(spaceval.join(' ')+" "+val.join(', '))
});
});
Add a class spaceNeeded to html elements :
<input class="combine spaceNeeded" id="input1" disabled="true" value="Happy"></input>
DEMO

$(document).ready(function () {
$('#LaserSword').on('click', function () {
var res = []
$('.combine').not('#Voltes5').each(function() {
res.push($(this).val())
})
$('#Voltes5').val(res.join(',').replace(/,/, ' '))
});
});
demo

Related

How do you save multiple key value pairs to one cookie with JavaScript/jQuery?

I have a form with multiple checkboxes in it and when I click them, I want to add/remove the key-value pairs (name of the input + true/false) in one single cookie.
When I click on the checkboxes only the first pair gets shown in console.log.
This is what I ended up with so far:
HTML:
<form class="form">
<input class="input" name="expert_id_1" type="checkbox" />
<input class="input" name="expert_id_2" type="checkbox" />
<input class="input" name="expert_id_3" type="checkbox" />
<input class="input" name="expert_id_4" type="checkbox" />
</form>
JS:
function setCookie() {
var customObject = {};
var inputName = $('.input').attr('name');
customObject[inputName] = $('.input').prop('checked');
var jsonString = JSON.stringify(customObject);
document.cookie = 'cookieObject=' + jsonString;
console.log(jsonString);
}
function getCookie() {
var nameValueArray = document.cookie.split('=');
var customObject = JSON.parse(nameValueArray[1]);
$('.input').prop('checked') = customObject[inputName];
}
$('.input').each(function() {
$(this).on('click', function() {
if ($(this).is(':checked')) {
$(this).attr('value', 'true');
} else {
$(this).attr('value', 'false');
}
setCookie();
});
});
Your cookie is being overrided and it might only store the first checkbox info. Also to set the prop value, you have to pass it as a second parameter.
This should update the cookie when clicked and also be able to set the values from the cookie.
function updateCookie($input) {
var cookieObject = getCookieObject();
var inputName = $input.attr('name');
cookieObject[inputName] = $input.attr('value');
var jsonString = JSON.stringify(cookieObject);
document.cookie = 'cookieObject=' + jsonString;
console.log(jsonString);
}
function setFromCookie(){
var cookieObject = getCookieObject();
for(var inputName in cookieObject)
if(cookieObject.hasOwnProperty(inputName))
$(`.input[name="${inputName}"]`).prop('checked', cookieObject[inputName]);
}
function getCookieObject() {
var nameValueArray = document.cookie.split('=');
var cookieObject = {};
if(nameValueArray.length >= 2)
cookieObject = JSON.parse(nameValueArray[1]);
return cookieObject;
}
$('.input').each(function() {
var $this = $(this);
$this.on('click', function() {
$this.attr('value', String($this.is(':checked')))
updateCookie($this);
});
});
Although I would recomend you to use a URLSearchParams object to encode and decode the parameters, since you are relying on the fact that "=" is not inside the JSON string.

Read the value of input returns undefined

I have this input
<input id="look" type="number" min="0" step="0.01" max="100000" class="form-control" name="number" required>
and I want to read the value that user will put at that time. So I wrote
$(function() {
$('#look').on('keyup', function(e) {
var temp2 = $('look').val();
alert(temp2);
});
});
and when the user starts typing the value inside the alert is undefined..
it should be #look rather than look, but rather than a selector use $( this )
$(function() {
$('#look').on('keyup', function(e) {
var temp2 = $(this).val(); //look should have been #look
alert(temp2);
});
});
$('#look').on('keyup', function(e) {
var temp2 = $('#look').val(); // you are missing #
alert(temp2);
});
Try this :
$(function() {
$('#look').on('keyup', function(e) {
var temp2 = $('#look').val(); //# is used for id selectors
alert(temp2);
});
});
while you are getting value from the input field, you missed "#" before ID.
replace
var temp2 = $('look').val();
with
var temp2 = $('#look').val();
or you can use $(this).val()

I want to disable the button if specific text has been found in any label

I want to disable the button if specific text has been found in any label.
The following code doesn't run because aTags[i].innerText is not equal to searchText all the time which is wrong because the label has inner text = "a" and the searchText variable have "a" as text - I need it to run in IE
<html>
<script language="javascript">
$(document).ready(function () {
var aTags = document.getElementsByTagName("label");
var searchText = "a";
var found;
for (var i = 0; i < aTags.length; i++) {
if (aTags[i].innerText == searchText) {
document.getElementById('choose').disabled=true;
break;
}
else
{
alert("failed")
}
}
});
</script>
<label> a </label> <br/>
<label> b </label> <br/>
<label> c </label> <br/>
<input type='button' value='choose' id='choose' />
</html>
Seems like there should be easier ways to do that with jQuery
$(function () {
var searchText = "a";
$('#choose').prop('disabled', function() {
return $('label').filter(function(_,el) {
return $.trim( $(el).text() ) === searchText;
}).length > 0;
});
});
FIDDLE
The issue is that your label contains " a " (with the spaces), but you're comparing with "a" (no spaces).
If you want to ignore the spaces, you can use jQuery's $.trim(...) to trim the text off the innerText.
But as you're using jQuery, you can dramatically reduce that code:
$(document).ready(function() {
var searchText = "a";
var found = false;
$("label").each(function() {
found = $.trim($(this).text()) === searchText;
if (found) {
return false; // No need to keep looking
}
});
$("#choose").prop("disabled", true);
});
Since you're already using jQuery, you can do what you like with much less complexity.
This will work:
(function ($) {
var searchText = "a";
$('label').each(function(){
if ($.trim($(this).text()) === searchText) {
$('#choose').prop('disabled', true);
}
});
})(jQuery);
You have to trim label's text. Try with:
if (aTags[i].innerText.trim() == searchText)
or without trim method:
if (aTags[i].innerText.replace(/^\s+|\s+$/g, '') == searchText)
If you want to match if a substring exists you can try with
aTags[i].innerText.indexOf(searchText) > -1
instead of
aTags[i].innerText == searchText

How to make localstorage of focus in textbox using Jquery dynamic?

<input id="input1" type="text" />
<br />
<input id="input2" type="text" />
I have followed this simple script that stores the focus on the input text.
$(document).ready(function() {
changeFocus();
$("#input1").click(function(){
localStorage.setItem('txtObjectid', "input1");
changeFocus();
return false;
});
$("#input2").click(function(){
localStorage.setItem('txtObjectid', "input2");
changeFocus();
return false;
});
});
function changeFocus(){
if(localStorage.getItem('txtObjectid')==null)
id="input1"
else
id=localStorage.getItem('txtObjectid');
var v = "#" + id;
$(v).focus();
}
What I want to learn/know about is how to make the script flexible? How could I make this so that it won't search of the id = "input1" instead it will search for input[type=text]?
Something like this should do it
$(document).ready(function () {
var id = 'input1';
if (localStorage.getItem('txtObjectid')) {
id = localStorage.getItem('txtObjectid');
}
$('#' + id).focus();
$('input[type="text"]').on('focus', function () {
localStorage.setItem('txtObjectid', this.id);
});
});
FIDDLE

What's the best way to update the input names when dynamically adding them to a form?

I'm trynig to come up with a clean and efficient way of handling form input names when dynamically adding more to the POST array.
For example, if I have the following form:
<fieldset>
<input type="text" name="users-0.firstname" />
<input type="text" name="users-0.lastname" />
</fieldset>
I then click an 'addmore' button which duplicates that HTML and adds it back into the document. Resulting in:
<fieldset>
<input type="text" name="users-0.firstname" />
<input type="text" name="users-0.lastname" />
</fieldset>
I'm trying to find the best way to increment that name index so I can use the data on the server. So far, I've been using the following code:
$('.addmore').click(function()
{
var $button = $(this);
var $fieldset = $button.prev('fieldset');
var $newset = $('<div class="new">' + $fieldset[0].innerHTML + '</div>');
$newset.insertBefore($button);
updatenames($newset, $('fieldset').length + 1);
});
function updatenames($set, newIndex)
{
/*
updates input names in the form of
set-index.name
set-index
*/
var findnametype = function(inputname)
{
if (inputname.indexOf('-') != -1 && inputname.indexOf('.') != -1)
{
var data1 = inputname.split('-');
var data2 = data1[1].split('.');
// [type, set, index]
return [1, data1[0], parseInt(data2[0])]
}
if (inputname.indexOf('-') != -1 && inputname.indexOf('.') == -1)
{
var data = inputname.split('-');
return [2, data[0], data[1]];
}
return false;
};
var type = findnametype($set.find('input:eq(0)')[0].name);
$set.find('input, select').each(function()
{
var $input = $(this);
var oldname = $input[0].name;
var newname = false;
switch (type[0])
{
case 1: newname = oldname.replace('-' + type[2], '-' + newIndex);
break;
case 2: newname = oldname.replace('-' + type[2], '-' + newIndex);
break;
}
$input[0].name = newname;
});
return type;
}
That updatenames function is a variation of what I've been using lately. In this case, I check to find the format of the input name. I then increment the index.
The incrementing, as you've probably noticed, happens in the DOM. As a 'part 2' to my question, I'd like to learn how to have that object returned for me to then insert into the DOM.
Something like:
$newset = updatenames($newset, $('fieldset').length +1);
$newset.insertBefore($button);
Your help is appreciated. Cheers.
Have you considered using array-based field names? You wouldn't have to alter those at all:
<input type="text" name="users.firstname[]" />
<input type="text" name="users.lastname[]" />
whether this works for you will of course depend on what you're going to do with the fields.
<script type="text/javascript">
$(document).ready(function () {
$('.addmore').click(function () {
var fieldset = $(this).prev('fieldset');
var newFieldset = fieldset.clone();
incrementFieldset(newFieldset);
newFieldset.insertBefore($(this));
});
});
function incrementFieldset(set) {
$(set).find('input').each(function () {
var oldName = $(this).attr('name');
var regex = /^(.*)-([0-9]+)\.(.*)$/;
var match = regex.exec(oldName);
var newName = match[1] + '-' + (parseInt(match[2]) + 1) + '.' + match[3];
$(this).attr('name', newName);
});
}
</script>
<fieldset>
<input type="text" name="users-0.firstname" />
<input type="text" name="users-0.lastname" />
</fieldset>
<input type="button" class="addmore" value="Add" />
<fieldset>
<input index=1 var=user prop=firstname />
<input index=1 var=user prop=lastname />
</fieldset>
<fieldset>
<input index=2 var=user prop=firstname />
<input index=2 var=user prop=lastname />
</fieldset>
before you submit your form
get the custom attributes and construct your 'name' attribute
[update]
its jsp but shouldn't be hard for u to convert to php
<%
for (int i = 0; i < 1000; i++) {
%>
<fieldset>
<input index=<%=i%> var=user prop=firstname />
<input index=<%=i%> var=user prop=lastname />
</fieldset>
<%
}
%>
for the js code
$('button').click(function(){
$('input').each(function(i, node){
var $node = $(node);
$node.attr('name', $node.attr('var') + $node.attr('index') + "."+ $node.attr('prop'))
});
});

Categories

Resources