How to remove a defined text character from element? - javascript

I need to remove y from the text character:
My mark up:
<label>
<input type="checkbox" name="_sft_category[]" value="" data-sf-cr="_sft_31" data-sf-hide-empty="1"> y2012 <span class="sf-count">(8)</span>
</label>
it has to become 2012 and I am trying the following but with no luck
$('label input').text(function() {
var text = $(this).text();
return text.indexOf('y') == 0 ? text.substring(1) : text;
});
There is a blank space in my text output, I wonder if that has something to do as it is " y2012 "

You are not setting value again in input
$('label input').text(function() {
var text = $(this).text();
text = text.replace('y','');
$(this).val(text);
});

Note: If you can change the original markup instead of fixing it using javascript that will be better.
In this case it is not the input element's text, it is the contents of a text node so
var $input = $('label input'),
elTxt = $input[0].nextSibling;
elTxt.nodeValue = elTxt.nodeValue.replace(/^(\s)?y/, '$1')
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<label>
<input type="checkbox"> y2012
</label>

Use this:
return text.replace("y", "")

Related

how to get two word from a input field and make url based on another field

here i have two input field as like
$(document).ready(function() {
$("#business_name").keyup(function() {
var Text = $(this).val();
Text = Text.toLowerCase();
Text = Text.replace(/[^a-zA-Z0-9]+/g,'-');
$("#business_url").val(Text);
});
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<input type="text" id="business_name" name="business_name" placeholder="Business Name" />
<br><br>
<input type="text" id="business_url" name="business_url" placeholder="Business URL" />
now I want if someone wrote : My Business Name on first input field then 2nd field it will be write mybusiness thats it but now it showed my-business-name i dont want this (I need only two word if it will take longer name then it only shows first two word thats it )
To get only the first two words you can split() the string in to an array by spaces and then use slice() to get the first two elements of the resulting array. Then you can join it back together before displaying in the input.
Also note I added trim() and a regex to replace multiple whitespace with a single one, otherwise it would affect how split() builds the array and could end up missing words.
jQuery($ => {
$("#business_name").on('input', e => {
var text = $(e.target).val().trim().replace(/\s+/, ' ').toLowerCase().split(' ').slice(0, 2).join('');
$("#business_url").val(text);
});
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<input type="text" id="business_name" name="business_name" placeholder="Business Name" /><br /><br />
<input type="text" id="business_url" name="business_url" placeholder="Business URL" />
After replacing certain characters with ' ' count the number of ' ' in the string. If the count is 2 stop replacing or you can return from the function.
Look at the modified code below:
$(document).ready(function() {
var count = 0;
$("#business_name").keyup(function() {
var Text = $(this).val();
Text = Text.toLowerCase();
Text = Text.replace(/[^a-zA-Z0-9]+/g,' ');
count = (Text.split("-")).length - 1;
if (count == 2) {
return;
}
$("#business_url").val(Text);
});
});

How to wrap price in span regexp?

I'm trying to wrap the price of an item in a span. Right now the RegExp wraps the numbers but not the $ (dollar sign). I need a regex that wraps the entire price.
HTML
<fieldset>
<label>
<input>Thing $4.99</input>
</label>
</fieldset>
JQUERY
var rxp = new RegExp("([0-9]+\.?[0-9]+)", "gm");
$( "fieldset label" ).each(function() {
var $this = $(this);
var content = $this.html();
console.log($(this).html());
$this.html(content.replace(rxp, "<span>$1</span>"));
});
This is not the correct way to do it. html() method will return you html markup, but changing it will not change the DOM. Instead you should empty your parent and append new span in it. Also you are using input tag in a wrong way, it can't have children, you should set value to value attr:
// HTML
<fieldset>
<label>
<input value="Thing $4.99" />
</label>
</fieldset>
// JavaScript
var priceRegExp = /^.*(\$[0-9](\.[0-9]{2})?).*$/;
$("fieldset label").each(function() {
var $this = $(this);
var inputVal = $this.children('input').prop('value');
var price = priceRegExp.exec(inputVal)[1];
$this.empty().append('span').text(price);
});

How to automatically change a specific text value with an input value?

What I'm trying to achieve is that when I'm entering an input value, the specific number of a textarea's value would replaced too according to the input value.
F.e: If I would enter into the input value a number 4, textarea's specific value (in this case a number) would be 4 too. If I would delete a value from the input, the value would be deleted from textarea too.
As you can see in the snippet, it works bad. It changes a value just one time. After that, 'text-areas' value isn't changing.
Could someone help me with that? Thank you for your time
$('.text1').keyup(function() {
var recommendationText = $('.textarea');
var specificString = '4';
var str = $('.textarea').val().replace(specificString, $(this).val());
recommendationText.val(str);
specificString = $(this).val();
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<input type="text" class="text1">
<textarea rows="4" class="textarea" cols="50">
This is a textarea of 4 rows.
</textarea>
There are a couple of issues with your code. The first is that the specificString value is being reassigned each time you do a keyup, so you need to set the default outside of the event handler. But also, if you delete the value, it will have no way of finding it and will prepend it to the start.
I'd personally recommend using a template based approach, rather than storing the previous value:
var specificString = '[numRows]';
var recommendationText = $('.textarea').val();
$('.text1').keyup(function() {
var numRows = $(this).val();
if (isNaN(parseFloat(numRows)) || !isFinite(numRows) || numRows.length < 1) {
numRows = 0;
}
var str = recommendationText.replace(specificString, numRows);
$('.textarea').val(str);
}).keyup();
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<input type="text" class="text1" value="4">
<textarea rows="4" class="textarea" cols="50">
This is a textarea of [numRows] rows.
</textarea>
This could use a proper templating language like Handlebars or Underscore.js templates, but that is too opinion-based to include in my answer.
Declare and initialize specificString outside of keyup() event.Otherwise your value for specificString will be always 4.
var specificString = '4';
$('.text1').keyup(function() {
var recommendationText = $('.textarea');
var str = $('.textarea').val().replace(specificString, $(this).val());
recommendationText.val(str);
specificString = $(this).val();
});
Well your issue is you replace the string so next time you look for the 4 it is not there. Reason why is you redefine specificString inside of the loop so it is always 4 and not what the user last typed. So if you move it outside it will work ("sort of")
Your design will fail if the user enters in something that matches another word. EG This, it will replace the first occurrence, not the string you want to replace. Or if you delete the string, you will not have any match.
So what can you do? I would use a data attribute with the original and use that. And I would make some sort of "template" so you know what you are replacing and do not replace another part of the string with the replacement when user matches text.
$('.text1').keyup(function() {
var ta = $('.textarea')
var specificString = /\{4\}/;
var entry = $(this).val() || "4";
var str = ta.data("text").replace(specificString, entry);
ta.val(str);
}).trigger("keyup");
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<input type="text" class="text1">
<textarea rows="4" class="textarea" cols="50" data-text="This is a textarea of {4} rows.">
</textarea>
In your way your code would work. Just change your code like this..! There are some logical issues in your code. Initiate the value of specificString outside the keyup() method to get first 4 and then then the value of textbox.
var recommendationText = $('.textarea');
var specificString = recommendationText.val().match(/\d+/);
$('.text1').keyup(function() {
if($(this).val() != '' && $.isNumeric($(this).val())) {
var str = $('.textarea').val().replace(specificString, $(this).val());
recommendationText.val(str);
specificString = $(this).val();
}
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<input type="text" class="text1">
<textarea rows="4" class="textarea" cols="50">
This is a textarea of 4 rows.
</textarea>
Solution is much easier than you might expect.
Note: The $ in ${inputVal} is not jquery, its part of template literals. Don't get confused there.
document.getElementById('text1').onkeyup = changeTextArea;
function changeTextArea() {
let inputVal = document.getElementById('text1').value;
let text = `This is a textArea of ${inputVal} rows`;
document.getElementById("textarea").value = text;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<input type="text" id="text1">
<textarea rows="4" id="textarea" cols="50">
This is a textarea of 4 rows.
</textarea>

Add <span> to part of a label using jQuery

I'm trying to add a span to only part of a label using jQuery. I'm able to isolate the section I want to add the span to (view my fiddle and inspect via the console), but now that I've got that, I don't know how to add the actual span. I need this in order to style a specific section of the label (in this case "red" as an example). Unfortunately, the markup is dynamically generated, so I can't just manually add it.
Here's my fiddle.
Here are my watered-down code snippets if you'd prefer to view them here:
HTML:
<input type="checkbox" /><label> Some Number (XXXXXX1234)</label><br />
<input type="checkbox" /><label> Some Other Number (XXXXXX4567)</label><br />
<input type="checkbox" /><label> Some Number (XXXXXX7890)</label>
CSS:
span {
color: red;
}
JS:
var label = $('label');
$.each(label, function() {
var arr = $(this).text().split(' '),
num = arr[arr.length-1];
console.log(num);
});
This is what I'm starting with:
<input type="checkbox" /><label> Some Number (XXXXXX1234)</label><br />
And this is what I'm trying to achieve:
<input type="checkbox" /><label> Some Number <span>(XXXXXX1234)</span></label><br />
There will by multiple inputs throughout the site, hence $.each.
I've found partial answers to this dilemma on Stack Overflow, just not the right combination to complete the task.
Match it with a regex and insert the spans in strings returned to the html() function
$('label').html(function(_,html) {
return html.replace(/(\(.*?\))/, "<span>$1</span>");
});
FIDDLE
If you want to split on spaces and get the last part, you can do that instead
$('label').html(function(_,html) {
var parts = html.split(" ");
var last = parts.pop();
parts.push('<span>', last, '</span>');
return parts.join(" ");
});
FIDDLE
Finishing up the approach you started with: set the element text to everything before the last section, then append the span and its contents:
var label = $('label');
$.each(label, function() {
var el = $(this),
arr = el.text().split(' '),
num = arr[arr.length - 1],
rest = arr.slice(0, arr.length - 1).join(' ');
el.
text(rest + " ").
append($('<span>').text(num));
});
span {
color: red;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<input type="checkbox" />
<label>Some Number (XXXXXX1234)</label>
<br />
<input type="checkbox" />
<label>Some Other Number (XXXXXX4567)</label>
<br />
<input type="checkbox" />
<label>Some Number (XXXXXX7890)</label>
Try the below working code snippet.I hope it will solve the issue
var label = $('label');
$.each(label, function() {
var arr = $(this).text().split(' '),
num = arr[arr.length-1], modifiedText = '<span>'+num+'</span>', finalText= $(this).text().replace(num, modifiedText);
$(this).html(finalText)
});

how to convert form text input to ASCII in Javascript?

how to convert text input to ASCII and display in text area..
HTML
<div class="form-group">
<label for="exampleInputPassword1">Favorite Food</label>
<input type="text" class="form-control" id="fFood" placeholder="Favorite Food" required>
<textarea name="txt_output"></textarea>
</div>
I assume what you want mean is to display the "text" typed in textBox in textArea
If so, and here you go: try here by clicking the button to display text in text area
The JS:
function display(){
var result = document.getElementById('fFood');
var txtArea = document.getElementById('textArea');
txtArea.value = result.value;
}
EDIT if you want to get the ASCII code from a string: try it here.
source of reference
If what you mean is how do you get the character code of a character from a javascript string, then you would use the string method str.charCodeAt(index).
var str = "abcd";
var code = str.charCodeAt(0);
This will technically be the unicode value of the character, but for regular ascii characters, that is the same value as the ascii value.
Working demo: http://jsfiddle.net/jfriend00/ZLRZ7/
If what you mean is how you get the text out of a textarea field, you can do that by first getting the DOM object that represents that object and then by getting the text from that object:
var textareas = document.getElementsByName("txt_output");
var txt = textareas[0].value;
If you then want to put that text into the input field, you can do that with this additional line of code:
document.getElementById("fFood").value = txt;
jquery
$(function(){
$('input[type=text]').keyup(function(){
var x = $('input[type=text]').val();
$('textarea').val(x);
});
});
javascript
<script>
function myFunction()
{
var x = document.getElementById("fFood").value;
document.getElementById("ta").value=x;
}
</script>
and html
<div class="form-group">
<label for="exampleInputPassword1">Favorite Food</label>
<input type="text" class="form-control" id="fFood" onkeyup="myFunction()" placeholder="Favorite Food">
<textarea name="txt_output" id="ta"></textarea>
</div>

Categories