jQuery selectors - more elegant solution - javascript

Given the following HTML fragment:
<div class="word">
<input type="text" name="A" />
<input type="text" name="n" />
</div>
<div class="word">
<input type="text" name="E" />
<input type="text" name="x" />
<input type="text" name="a" />
<input type="text" name="m" />
<input type="text" name="p" />
<input type="text" name="l" />
<input type="text" name="e" />
</div>
I'd like to write a jQuery script that would concatenate all the ':text' elements' names in a single string, while adding a space when reaching the end of a 'div.word' element.
For example, given the HTML above, the result would be:
An Example
Using my (very) limited jQuery/javascript skills I managed to find a solution, but it involves dirty for ... in loops, so I'd rather not show it here :-).
I'd like to know what is a more elegant/idiomatic (and probably more concise) solution to this problem.

Here's a DEMO: http://jsfiddle.net/ZRukk/1/
var string = $('.word input').map(function() {
var is_last = $(this).is(':last-child');
return this.name + (is_last ? ' ' : '');
}).toArray().join('');
In modern browsers, you could do it without jQuery like this...
Here's a DEMO: http://jsfiddle.net/ZRukk/4/
var inputs = document.querySelectorAll('.word input');
var string = [].map.call(inputs, function(el) {
return el.name + (!el.nextElementSibling ? ' ' : '');
}).join('');

You can do it like this:
var result = [];
$('.word').each(function() {
$(this).find('input').each(function() {
result.push(this.name);
});
result.push(' ');
});
var answer = $.trim(result.join(''));
Working example here: http://jsfiddle.net/jfriend00/DNWSm/
And, a slightly different way of doing it that is probably faster because it's probably less DOM searching:
var result = [];
var lastParent;
$('.word input').each(function() {
// if starting a new parent, add a word separator
if (lastParent && lastParent != this.parentNode) {
result.push(' ');
}
result.push(this.name);
lastParent = this.parentNode;
});
var answer = result.join('');
Working example here: http://jsfiddle.net/jfriend00/bEBGQ/

Related

JavaScript string concatenation not working

This javascript code to concatenate isn't working. I tried an alert before closure of script tag, it's displayed but the code below that I want to display the result in third or different text field.
HTML:
<input type="text" id="field"><br>
<input type="text" id="str2"><br>
<input type="text" id="str3"><br>
<button onclick="concate()">Concatenate</button>
JavaScript:
var s=document.getElementById("field").value;
var t=document.getElementById("str2").value;
var st=document.getElementById("str3").value;
function concate()
{
st=s+t;
document.getElementById("str3").value.innerHTML=st;
console.log(st);
document.write(st);
}
There's no function .value.innerHTML should be :
document.getElementById("str3").value = st;
Also you should get the fields value inside function and close your function definition using }, check example bellow.
Hope this helps.
function concate()
{
var s=document.getElementById("field").value;
var t=document.getElementById("str2").value;
document.getElementById("str3").value=s+t;
}
<input type="text" id="field"><br>
<input type="text" id="str2"><br>
<input type="text" id="str3"><br>
<button onclick="concate()">Concatenate</button>
function concate() {
var s=document.getElementById("field").value;
var t=document.getElementById("str2").value;
var st=document.getElementById("str3").value;
// this is a standard way to concatenate string in javascript
var result = s+t;
document.getElementById("str3").value=result;
}
<input type="text" id="field"><br>
<input type="text" id="str2"><br>
<input type="text" id="str3" readonly><br>
<button onclick="concate()">Concatenate</button>

How can trim spaces in all inputs without adding methods or classes?

I'm trying to remove blank spaces from the begining and ending of inputs in general without adding a class or id or event
I tried this live demo but is using onchange event
<javascript>
function trim(el) {
el.value = el.value.
replace(/(^\s*)|(\s*$)/gi, ""). // removes leading and trailing spaces
replace(/[ ]{2,}/gi, " "). // replaces multiple spaces with one space
replace(/\n +/, "\n"); // Removes spaces after newlines
return;
}
</script>
<p>Search1: <input type="text" onchange="return trim(this)" /></p>
<p>Search2: <input type="text" onchange="return trim(this)" /></p>
<p>Search3: <input type="text" onchange="return trim(this)" /></p>
<p>Search4: <input type="text" onchange="return trim(this)" /></p>
<p>Search5: <input type="text" onchange="return trim(this)" /></p>
Somebody can help me about how to make all my inputs trim input values (CSS OR JAVASCRIPT) like this:
<script>
Here in this script will trim blank spaces starting or ending so don't need to add anything in the input
</script>
<input type="text" />
I tried this but is not working
$(.input).text().trim()
Please somebody can help me?.
Thanks in advance.
try $.trim on change input with type text:-
jQuery
$(function(){
$('input[type="text"]').change(function(){
this.value = $.trim(this.value);
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<p>Search1: <input type="text"/></p>
<p>Search2: <input type="text"/></p>
<p>Search3: <input type="text"/></p>
<p>Search4: <input type="text"/></p>
<p>Search5: <input type="text"/></p>
Vanilla
window.onload = function() {
var inputs = document.getElementsByTagName('input');
for (var i = 0; i < inputs.length; i++) {
if (inputs[i].type == 'text') {
inputs[i].onchange = function() {
this.value = this.value.replace(/^\s+/, '').replace(/\s+$/, '');
};
}
}
}
<p>Search1: <input type="text"/></p>
<p>Search2: <input type="text"/></p>
<p>Search3: <input type="text"/></p>
<p>Search4: <input type="text"/></p>
<p>Search5: <input type="text"/></p>
This is one of the easiest way i found :), it uses jquery hope it helps, it uses your function
The input have to be only:
<input type="text" name="name">
This automatically change all inputs, or you can asign to a class
function trim_text(el) {
el.value = el.value.
replace(/(^\s*)|(\s*$)/gi, ""). // removes leading and trailing spaces
replace(/[ ]{2,}/gi, " "). // replaces multiple spaces with one space
replace(/\n +/, "\n"); // Removes spaces after newlines
return;
}
$(function(){
$("textarea").change(function() {
trim_text(this);
});
$("input").change(function() {
trim_text(this);
});
});
Try this:
function trim(el) {
var trimmedValue = el.val().trim();
el.val(trimmedValue);
}
Your syntax for .trim() is wrong.
To trim a input's value you don't need any regex, just try to change this:
$(.input).text().trim();
to this:
$('input').val().trim();
input is not a class, so you don't have to put the dot before it. Then you have to include it inside ' '. The value of an input is given by val() method, not text().
This will only trim the input's value, you have to use this inside a function in order to make it works properly, as in the example above.

calculate values using entered formula

This is my html code:
<input id="R1" type="text" value="100">
<input id="R2" type="text" value="200">
<input id="formula" type="text" value="">
<input type="button" id="save" value="save">
Here the user enter formula value dynamically like R1+R2, (R1-R2)*100. I need to calculate final value using the formula.
Ex: If user enter value in formula field R1+R2; I need the result 300.
How do I calculate the value dynamically?
Check out this snippet, should work with any combo:
function calExpression() {
var f = document.getElementById('formula');
var inps = document.getElementsByTagName('input');
var expression = f.value.toUpperCase();//' '+f.value.replace(/([-\/\+\(\)])/g,' $1 ')+' ';
for (var i = 0; i < inps.length; i++) {
if (inps[i].id && inps[i].type && inps[i].type.toLowerCase() === 'text') {
expression = expression.replace(new RegExp('\\b'+inps[i].id+'\\b', 'ig'), inps[i].value);
}
}
eval('f.value = '+expression+';');
}
<input id="R1" type="text" value="100">
<input id="R2" type="text" value="200">
<input id="formula" type="text" value="">
<input type="button" id="save" value="save" onclick="calcExpression()">
You can use eval. This is the fastest and easiest solution, but you must be careful with it and check with regexp that formula has only R1, R2, (, ) and math operators in it.
Or (better solution) you can find a library to parse expressions, in example http://mathjs.org/docs/expressions/parsing.html
<input type="button" id="save" value="save" onclick="return calculate()">
<script>
function calculate() {
var val1 = document.getElementById('R1').value;
var val2 = document.getElementById('R2').value;
var result = +val1 + +val2;
document.getElementById('formula').value = result;
}
</script>
Because a problem occures with "+" you have to use +val1 + +val2
Infix to Prefix Conversion Algorithm:
Infix to Prefix Conversion
Prefix Evaluation Algorithm:
Prefix Evaluation Algorithm
Use help from these links.
You can use .eval() method which allow you to evaluates JavaScript code represented as a string. It's a really powerful method.
Then, you have to parse your formula. With this piece of code, you will be able to add expression like ((R1+R2) - (R1*3)) + 1 for example.
function calculate(){
var valid = true;
var regex = /(?:[a-z$_][a-z0-9$_]*)|(?:[;={}\[\]"'!&<>^\\?:])/ig;
var formula = document.querySelector('#formula').value;
var R1 = parseInt(document.querySelector('#R1').value);
var R2 = parseInt(document.querySelector('#R2').value);
formula = formula.replace(/R1/g, R1).replace(/R2/g,R2);
formula = formula.replace(regex, function (elm) {
return Math.hasOwnProperty(elm)
? "Math."+elm
: valid = false;
});
if (valid)
alert(eval(formula));
}
Then add onlick event on save button :
<input id="R1" type="text" value="100">
<input id="R2" type="text" value="200">
<input id="formula" type="text" value="">
<input type="button" id="save" value="save" onclick="calculate()">
Here is the Working Plunker

HTML javascript function issue. [object HTMLInputElement] error output

I am trying to make a simple html page with two text boxes and an a button that adds the two numbers together when clicked. In my output, I am only getting [object HTMLInputElement].
function addNumbers(A, B){
var answer = A + B;
document.getElementById("testResult").innerHTML = answer;
}
<input type="text" value="15" id="varA">
<input type="text" value="30" id="varB">
<input type="button" value="Add" onclick="addNumbers(varA, varB)">
<h1 id="testResult"></h1>
Any help would be appreciated. I tried changing .innerHTML to .value already but then I get nothing at all as a result.
I assume you want the mathematical sum and not the string concatenation. If that's the case, you can use the following:
UPDATE based on comment:
function addNumbers(elem1, elem2) {
var a = document.getElementById(elem1).value;
var b = document.getElementById(elem2).value;
var c = Number(a) + Number(b);
document.getElementById("testResult").innerHTML = c;
}
<input type="text" value="15" id="varA">
<input type="text" value="30" id="varB">
<input type="button" value="Add" onclick="addNumbers('varA', 'varB')"></input>
<h1 id="testResult"></h1>
Here's a working Fiddle: http://jsfiddle.net/JohnnyEstilles/ex09fx7k/.
Some fixes:
You are adding up the inputs elements instead of their value.
To convert its string value to a number, you can use unary +.
Instead of inline event listeners, better use addEventListener.
var a = document.getElementById('varA'),
b = document.getElementById('varB'),
result = document.getElementById("testResult");
document.getElementById('add').addEventListener('click', function() {
addNumbers(a.value, b.value);
});
function addNumbers(n1, n2){
result.textContent = +n1 + +n2;
}
<input type="text" value="15" id="varA">
<input type="text" value="30" id="varB">
<input type="button" id="add" value="Add">
<h1 id="testResult"></h1>

Javascript innerHtml and value for textbox and label issue

I have below javascript code.
var txtone = document.getElementByID("txtone");
var lblone = document.getElementByID("lblone");
var tone = txtone.value;
var lone = lblone.innerHTML;
Now the problem is there are cases when I dont have txtone or lblone in my page so in that case last two lines of my code gives error.
solution for this is to check if they exists might be like this code.
var txtone = document.getElementByID("txtone");
var lblone = document.getElementByID("lblone");
if(txtone)
var tone = txtone.value;
if(lblone)
var lone = lblone.innerHTML;
but In my case I have around 100 to 200 textbox and labels with are rendered based on some condition. So in that case I dont think the give solution will be the best one.
Is there any easy way out to my problem something like prototyping value or innerHtml.
(It is an aspx web site page)
Update answer
Check DEMO http://jsfiddle.net/tD6eC/1/
You can use without class or ID like that.
HTML
<label id="">label 1</label><input id="" value="1" /><br />
<label id="">label 2</label><input id="" value="2" /><br />
<label id="">label 3</label><input id="" value="3" /><br />
<label id="">label 4</label><input id="" value="4" /><br />
<label id="">label 5</label><input id="" value="5" /><br />
<div id="content"></div>
JQUERY
$(document).ready(function(){
var val, label;
$('label').each(function(){
val = $(this).html();
label = $(this).next('input').val();
if(val != 'undefined' && label != 'undefined'){
$('#content').append(val+' : '+label+'<br />');
}
});
});

Categories

Resources