How to replace label content with .each - javascript

I want to write a script that would resize labels length if its longer than 30 characters, but can't find the reason why it stays the same.
jsfiddle:
http://jsfiddle.net/rokas_m/9g3bcamz/10/
HTML:
<label>labelislabelislabelislabelislabelislabelislabelis</label><Br/>
<label>kitaskitaskitaskitaskitaskitaskitaskitaskitaskitaskitas</label><br/>
<label>asdfasdfsadfasdfsdfdsftaskitaskitaskitas</label><br/>
<label>siaip</label><br />
<label>siaip</label><br />
<label>siaip</label><br />
jQuery:
$('label').each( function(){
var string = $(this).text();
var ilgis = $(this).text().length;
if (ilgis > 30){
var string = string.substr(0,17)+'...';
$( 'label' ).innerHTML = string;
console.log(string);
}
}
);

You can use .text() set the value by passing a callback function as its argument which will be called for each label, like
$('label').text(function(i, text) {
return text.length > 30 ? text.substr(0, 17) + '...' : text;
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<label>labelislabelislabelislabelislabelislabelislabelis</label><Br/>
<label>kitaskitaskitaskitaskitaskitaskitaskitaskitaskitaskitas</label><br/>
<label>asdfasdfsadfasdfsdfdsftaskitaskitaskitas</label><br/>
<label>siaip</label><br />
<label>siaip</label><br />
<label>siaip</label><br />
Or
$('label').each(function() {
var string = $(this).text();
var ilgis = string.length; //reuse the variable
if (ilgis > 30) {
string = string.substr(0, 17) + '...';
$(this).html(string);//$(...) returns a jQuery object so don't have `innerHTML` property, also you need to target the current `label` not all of them
//or just
//this.innerHTML = string
console.log(string);
}
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<label>labelislabelislabelislabelislabelislabelislabelis</label><Br/>
<label>kitaskitaskitaskitaskitaskitaskitaskitaskitaskitaskitas</label><br/>
<label>asdfasdfsadfasdfsdfdsftaskitaskitaskitas</label><br/>
<label>siaip</label><br />
<label>siaip</label><br />
<label>siaip</label><br />

Replace this $( 'label' ).innerHTML = string; with $(this).html(string);.
Here's the modified code:
$('label').each( function(){
var string = $(this).text();
var ilgis = $(this).text().length;
if (ilgis > 30){
var string = string.substr(0,17)+'...';
$(this).html(string);
}
}
);

Refer this
$('label').each( function(){
var string = $(this).text();
var ilgis = $(this).text().length;
if (ilgis > 30){
var string = string.substr(0,17)+'...';
jQuery(this).html(string);
console.log(string);
}
}
);

Related

How to convert a string like 1/4 from a text box to numeric in javascript

How to convert a string like 1/4 from a text box to numeric in javascript.
<form>
<input type='text' name='inputText' value='1/4'>
</form>
<script>
var text=DOCUMENT.getElementsByName('inputText')[0].value;
</script>
How to convert text to numeric?
Without using eval, you could do this:
function convertValue(value) {
let parts = value.split("/");
let dividend = parseFloat(parts[0]);
let divisor = parseFloat(parts[1]);
if (isNaN(dividend) || isNaN(divisor) || divisor === 0) {
return "Cannot divide";
}
return dividend / divisor;
}
console.log(convertValue("1/4")); // 0.25
console.log(convertValue("10/2")); // 5
console.log(convertValue("-8/2")); // -4
console.log(convertValue("6/-2")); // -3
console.log(convertValue("0.5/0.25")); // 2
console.log(convertValue("a/b")); // Cannot divide
console.log(convertValue("5/0")); // Cannot divide
you could use eval() method for this:
var text = document.getElementsByName('inputText')[0].value;
document.getElementsByName('inputText2')[0].value = eval(text);
<form>
<input type='text' name='inputText' value='1/4'>
<input type='text' name='inputText2'>
</form>
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/eval
First sanitize the value
var fnSanitize = str => !"1/s4".match( /[^-+*/\d+]/g )
Above function will check if the value has anything else apart from 0-9 and +-*\. You can add more operators like () as well.
Now evaluate the expression
var evalExpression = str => fnSanitize( str ) ? eval( str ) : "";
Demo
var fnSanitize = str => !str.match(/[^-+*/\d+]/g)
var evalExpression = str => fnSanitize(str) ? console.log(eval(str)) : console.log("Bad expression");
document.querySelector("#check").addEventListener("click", function() {
evalExpression(document.querySelector("#inputText").value);
})
<form>
<input type='text' id='inputText' value='1/4'>
<button id="check">Check</button>
</form>
<script>
</script>
Or via Function constructor
var evalExpression = str => fnSanitize( str ) ? new Function( "return " str ) : "";
Demo
var fnSanitize = str => !str.match(/[^-+*/\d+]/g)
var evalExpression = str => fnSanitize( str ) ? console.log(new Function( "return " + str )()) : console.log("Bad expression");
document.querySelector("#check").addEventListener("click", function() {
evalExpression(document.querySelector("#inputText").value);
});
<form>
<input type='text' id='inputText' value='1/4'>
<button id="check">Check</button>
</form>
<script>
</script>
Evaluate it:
<form>
<input type='text' name='inputText' value='1/4'>
</form>
<script>
var text = eval(document.getElementsByName('inputText')[0].value);
console.log(text); // returns: 0.25
</script>

remove character from input field while user is typing (keyup)

I'm looking for a js or jq way to remove # character while user is typing on a field.
I tried this:
$( function() {
$( ".remove-sharp" ).on( "keyup", function( event ) {
console.log( 'test' );
$( this ).val().replace( /\#/, "" );
} )
} );
I can see the "test" being printed in console but this has no effect on the characters in the field; it doesn't remove #. How to achieve this ?
The issue is because you're not setting the value of the input, only getting it and making the replacement and doing nothing with the resulting string. Try this:
$(function() {
$(".remove-sharp").on("keyup", function(event) {
var value = $(this).val();
if (value.indexOf('#') != -1) {
$(this).val(value.replace(/\#/g, ""));
}
})
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input type="text" class="remove-sharp" />
function validateCustomerName(){
var validatedName = "";
var restrictedCharactersArray = ["0","1","2","3","4","5","6","7","8","9","~","`","!","#","#","$","%","^","&","*","(",")","-","_",
"+","=","{","}","[","]",":",";","'","<",">",",",".","?","/","/\/","|"];
var customerName = document.getElementById("customerName").value;
var numberValidation = (/^[a-zA-Z_ ]+$/g).test(customerName);
if(!numberValidation){
validatedName = "";
var customerNameArray = customerName.split("");
for(var i=0;i<restrictedCharactersArray.length;i++){
var restrictedCharacter = restrictedCharactersArray[i];
if(customerNameArray.indexOf(restrictedCharacter) !== -1){
for(var j=0; j<customerNameArray.length; j++){
var customerNameCharacter = customerNameArray[j];
if(customerNameCharacter !== restrictedCharacter){
validatedName = validatedName+customerNameCharacter;
}
}
}
}
document.getElementById("customerName").value = validatedName;
}
}
<input type="text" id="customerName" onKeyUp="validateCustomerName();" />

remove extra comma at the end of the line

I am working on limiting tags so max will be 5 but for this test I will use 2 however, at the end of the line there is an extra comma left when attempting to add another tag more than the max-allowable. How do I remove that comma?
<body>
<input id="input" type="text" />
</body>
$("#input").keypress(function(e){
var value = $(this).val().replace(" ", "");
var words = value.split(",");
if(words.length > 2){
//alert("Hey! That's more than 5 words!");
e.preventDefault();
}
});
DEMO: http://jsfiddle.net/BzN5W/2/
Here, try this :
$("#input").keypress(function(e){
var value = $(this).val().replace(" ", "");
var words = value.split(",");
if(words.length > 5){
alert("Hey! That's more than 5 words!");
$('#input').val($('#input').val().substring(0, $('#input').val().length-1));
e.preventDefault();
}
});
$("#input").keypress(function(e){
var value = $(this).val().replace(" ", "");
var words = value.split(",");
if(words.length > 5){
$(this).val(value.slice(0,value.length-1))
e.preventDefault();
}
});
Try this:
$("#input").keydown(function(e){
if(e.which === 188 && ($(this).val().match(/,/g) || []).length ==4){
e.preventDefault();
}
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<body>
<input id="input" type="text" />
</body>

Disallow special characters in textbox validation

I have javascript code where the validation does not allow more than 20 characters in text box. But, I also want to disallow in special characters in the validation; how can this be accomplished.
Here is my current validation code:
<script type="text/javascript" src="https://code.jquery.com/jquery-1.8.2.js">
/script>
<script type='text/javascript'>
$(function()
{ $('#QI4562040').keyup(function()
{
var desc = $('#QI4562040').val();
var len = desc.length;
if (desc.length >= 10)
{
this.value = this.value.substring(0, 10);
} $('#spntxt').text(10 - len + ' Characters Left');
});
}); </script>
try bellow script this will not allow special charter # $ % ^ & * ( )
function validate() {
var element = document.getElementById('input-field');
element.value = element.value.replace(/[^a-zA-Z0-9#]+/, '');
};
<input type="text" id="input-field" onkeyup="validate();"/>
I just use your codes and modify:
$(function()
{ $('#QI4562040').keyup(function()
{
var desc = $('#QI4562040').val();
var lastChar = desc.slice(-1);
var spc = !((lastChar.charCodeAt()>=48&&lastChar.charCodeAt()<=57)||(lastChar.charCodeAt()>=65&&lastChar.charCodeAt()<=90)||(lastChar.charCodeAt()>=97&&lastChar.charCodeAt()<=122));
if (desc.length >= 10 || spc)
{
this.value = this.value.substring(0, desc.length-1);
} $('#spntxt').text(10 - len + ' Characters Left');
});
});
You must use the keypress event
<input type="text" onkeypress="return isValidCharacter(event)" />
and define the javascript event, the validation can do it with regular expressions
function isValidCharacter(e) {
var key;
document.all ? key = e.keyCode : key = e.which;
var pressedCharacter = String.fromCharCode(e)
var regExp = /^[a-zA-ZÁÉÍÓÚáéñíóú ]*$/;
return regExp.test(pressedCharacter); }
If the method returns true the character will be printed
For Input Length, use Html5 Max Length Property
$(function(){
$('#QI4562040').keyup(function(){
var input_val = $(this).val();
var inputRGEX = /^[a-zA-Z0-9]*$/;
var inputResult = inputRGEX.test(input_val);
if(!(inputResult))
{
this.value = this.value.replace(/[^a-z0-9\s]/gi, '');
}
$('#spntxt').text(10 - input_val.length + ' Characters Left');
});
});
<input type='text' name='' id='QI4562040' maxlength='10'/>
<div id='spntxt'></div>
<script type="text/javascript" src="https://code.jquery.com/jquery-3.3.1.slim.min.js"></script>

javascript array to string conversion

I have this array in javascript:
[div.parts, div.editor, div.inside-1, div.container-2, div.inside-wrapper, div#content, div.whitebgpan, div, div#maindiv, body, html]
How can I convert it into string, so that the output will be:
div.parts div.editor div.inside-1 div.container-2 div.inside-wrapper div#content div.whitebgpan div div#maindiv body html
here is my code:
jQuery(document).on('click', function(e){
var ClickedParents = jQuery(e.target).parents(); //Get all parents of clicked element
var ClickedParents_array = jQuery.makeArray(ClickedParents); //Make array
console.log(ClickedParents_array); //Show output in colsole
});
You can use a combination of the jQuery each function and JavaScript's Array.Join function to solve this problem.
DEMO: http://jsfiddle.net/zay015ex/1/
I've artificially retrieved an array of jQuery objects to show how you can solve this, but the concept is common to your problem.
HTML
<div id="parent">
<div id="child1"></div>
<div id="child2"></div>
<div id="child3"></div>
<div id="child4"></div>
<div id="child5"></div>
</div>
JavaScript
var arrayOfObjects = $('#parent').children();
var ids = [];
$.each(arrayOfObjects, function(i, val)
{
ids.push(val.id);
});
var idString = ids.join(' ');
You can read up more on the jQuery each function here.
You can read up more on the JavaScript's Array.Join function
here.
===== Update =====
Ok, the following code is tested, just open a console and paste this. it selects all div tags and convert into selector string.
$.map($('div'),function toSelector(elem){
var jqObj = $(elem)
var tag = jqObj.prop('tagName').toLowerCase()
var classes = jqObj.attr('class') ? '.' + jqObj.attr('class').split(' ').join('.') : ''
var ids = jqObj.attr('id') ? '#' + jqObj.attr('id').split(' ').join('#'): ''
return tag + classes + ids
})
===================
Supposing they're jquery objects, you have to build the string manually.
For example, do something like following. (not tested)
function toSelector(jqObj){
var tag = jqObj.prop('tagName').toLowerCase()
var classes = jqObj.attr('class') ? '.' + jqObj.attr('class').split(' ').join('.') : ''
var ids = jqObj.attr('id') ? '#' + jqObj.attr('id').split(' ').join('#'): ''
return tag + classes + ids
}
array.map(toSelector)
I think below code is helpful for you.
<script type="text/javascript">
String.prototype.replaceAll = function ( token, newToken, ignoreCase ) {
var _token;
var str = this + "";
var i = -1;
if ( typeof token === "string" ) {
if ( ignoreCase ) {
_token = token.toLowerCase();
while( (
i = str.toLowerCase().indexOf(
token, i >= 0 ? i + newToken.length : 0
) ) !== -1
) {
str = str.substring( 0, i ) +
newToken +
str.substring( i + token.length );
}
} else {
return this.split( token ).join( newToken );
}
}
return str;
};
try{
var arr = [];
arr.push('div.parts', 'div.editor', 'div.inside-1', 'div.container-2', 'div.inside-wrapper', 'div#content', 'div.whitebgpan', 'div', 'div#maindiv', 'body', 'html');
var stringData = arr.toString();
stringData = stringData.replaceAll(",", " ");
console.log(stringData);
}catch(e){
alert(e)
}
</script>

Categories

Resources