On keypress in a textarea, I need to select the id and separate it. How is this possible?
If I have some jQuery code:
$(document).on("keypress", "textarea", function(){$(this).
How can I get the textarea's id and separate it like if the id is id="ta1"
Assuming you are just interested in the numeric value part of the ID, you could easily strip off all non-numeric characters using a Regular Expression using the replace() function :
$('textarea').keypress(function(){
// Get your ID
var id = $(this).attr('id');
// Strip off any non-numeric values
var idNumber = id.replace(/\D+/g, '');
});
Working Example
$('textarea').keypress(function() {
// Get your ID
var id = $(this).attr('id');
// Strip off any non-numeric values
var idNumber = id.replace(/\D+/g, '');
alert('<textarea> #' + idNumber + ' was typed in');
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<pre>Text Area 1</pre>
<textarea id='ta1'></textarea>
<hr />
<pre>Text Area 2</pre>
<textarea id='ta2'></textarea>
<hr />
<pre>Text Area 3</pre>
<textarea id='ta3'></textarea>
try this
$('body').on('keypress','textarea',function(){
var id = $(this).attr('id')
var ta = id.substring(0,2);
var num = id.substring(2);
});
Related
I have a div in which I render through javascript inputs and text dynamically. I am trying to capture the text of this div (both input values and text).
My first step if to capture the parent div:
let answerWrapper = document.getElementById("typing-answer-wrapper");
The issue now is that using the innerHTML will give me the whole html string with the given tags and using the inerText will give me the text, excluding the tags.
In the following case scenario:
the console inspect is:
What is the way to capture: $2.4 if the inputs have 2 and 4
and $null.null if the inputs are blank.
Any help is welcome
You could iterate over all of the element's child nodes and concatenate their wholeText or value else 'null'. For inputs the wholeText will be undefined. If they have no value we'll return 'null'. Be aware that spaces and line-breaks will also be included so you may want to strip these later (or skip them in the loop) but as a proof of concept see the following example:
var typingAnswerWrapper = document.getElementById("typing-answer-wrapper");
function getVal(){
var nodeList = typingAnswerWrapper.childNodes;
var str = "";
for (var i = 0; i < nodeList.length; i++) {
var item = nodeList[i];
str+=(item.wholeText || item.value || "null");
}
console.log(str);
}
getVal();
//added a delegated change event for demo purposes:
typingAnswerWrapper.addEventListener('change', function(e){
if(e.target.matches("input")){
getVal();
}
});
<div id="typing-answer-wrapper">$<input type="number" value=""/>.<input type="number" value="" />
</div>
Here's how you could do it :
function getValue() {
var parent = document.getElementsByClassName('typing-answer-wrapper')[0],
text = [];
const children = [...parent.getElementsByTagName('input')];
children.forEach((child) => {
if (child.value == '')
text.push("null")
else
text.push(child.value)
});
if (text[0] != "null" && text[1] == "null") text[1] = "00";
document.getElementById('value').innerHTML = "$" + text[0] + "." + text[1]
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.js"></script>
<div class="typing-answer-wrapper">
$
<input type="number"> .
<input type="number">
</div>
<button onclick="getValue()">get value</button>
<div id="value"></div>
You can fetch input feild values by their respective ids $('#input_feild_1').val() will give the first feild value and similarly $('#input_feild_2').val() for second feild and contruct use them to construct whatever as u wish. As in your case this should work
value_1 = $('#input_feild_1_id').val()
value_2 = $('#input_feild_2_id').val()
you need something like "$ + value_1 + . + value_2"
I have a variable that contains HTML.
var html = '<p><span id="variable:7" class="variable-source" title="variable:TEXT_CONTAINER">DATA</span> This is a variable</p>'+
'<p><span id="input:10.New Input 2" class="input-source" title="New Screen; New Input 2">DATA</span> This is a input source</p>'+
'<p>Testing</p>';
I am trying to loop around all of the elements and replace with spans specific date. So any spans with a class of variable-source will need to be replaced with specific date, and the same for input-source.
I have tried to use the following:
$('span', html).replaceWith(function () {
var id = $(this).attr('id');
// this returns the correct id
//calculations go here
var value = 'testing';
return value
});
Which outputs the following:
testing This is a variable
All of the paragraph tags have been removed, and it seems to stop after the first paragraph. Is there something that I am missing here? I can post more code or explain more if needed.
Thanks in advance.
You need to create a html object reference, else you won't get a reference to the updated content. Then get the update content from the created jQuery object after doing the replace operations
var html = '<p><span id="variable:7" class="variable-source" title="variable:TEXT_CONTAINER">DATA</span> This is a variable</p>' +
'<p><span id="input:10.New Input 2" class="input-source" title="New Screen; New Input 2">DATA</span> This is a input source</p>' +
'<p>Testing</p>';
var $html = $('<div></div>', {
html: html
});
$html.find('span.variable-source').replaceWith(function() {
var id = this.id;
// this returns the correct id
//calculations go here
var value = 'replaced variable for: ' + id;
return value
});
$html.find('span.input-source').replaceWith(function() {
var id = this.id;
// this returns the correct id
//calculations go here
var value = 'replaced input for: ' + id;
return value
});
var result = $html.html();
$('#result').text(result);
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="result"></div>
I have to add an id to an element. An engine generates the HTML... I have no access to it. It generates random IDs as such:
<input id="5352Adkdie4929888a">
I want to grab the first instance of "<input id=" and replace the ID it has with
the ID it has + DatePicker.
Example:
<input id="5352Adkdie4929888a DatePicker">
How would I go about doing this?
My code so far:
function addID(){
var html= document.documentElement.innerHTML;
var start= '<input id="';
var end= '"'
var htmlIWant=html.substring(html.indexOf(start) + start.length), html.indexOf(end)-1 + 'DatePicker';
}
Am I on the right track? How do I actually replace the HTML? Thanks!
This is a pure javascript solution as per your requirements.
Assuming that your page will have many input tags and some of them will be without ID attribute below is a solution you can try.
var elements = document.getElementsByTagName("input");
for (var i = 0; i < elements.length; i++)
{
if (elements[i].type == "text" && elements[i].hasAttribute("id"))
{
var id = elements[i].getAttribute("id");
elements[i].setAttribute("id", id + "10");
break;
}
}
Grab the first input inside the element using
$('input:first-child').attr('id','whateverIdName');
If you have to catch first input box that has id attribute, you should do :
$("input[id]")[0]
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
I'm trying to loop through all elements that contain a certain data attribute and then replace/remove certain characters.
//replace chars put in by money mask since model is double
$("input[data-input-mask='money']").each(function() {
alert(this.value); // shows: $ 1,000
alert('test$ ,'.replace('$ ', '').replace(',', '')); //shows: test
this.value = this.value.replace('$ ', '').replace(',', '');
alert(this.value); //shows: $ 1,000
});
this.value is still the original value. What might I be doing wrong here?
Use .localeString()
UPDATE
After rereading the OP, I realize the opposite is desired. That's still easy. Instead of using a mask, use localString(). Then it's a matter of not using localestring() when you processing the values.
SNIPPET
$("input[data-input-mask='money']").each(function() {
var cash = parseFloat(this.value);
var green = cash.toLocaleString('en-EN', { style: 'currency', currency: 'USD' });
alert(green);
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input data-input-mask='money' value="623.23">
<input data-input-mask='money' value="20199">
<input data-input-mask='money' value="">
You can loop through each element and replace it like this.
<script>
$(document).ready(function(e) {
//Retrieve all text of amount di;
$.each( $('.amount'), function(){
var unique_id = $(this).text();
//check if any price is match to FREE THEN replace it with NOT FREE
if(unique_id=='FREE'){
$(this).text("NOT FREE");
}
});
});
</script>
how can concatenate the set variable in a for loop to be use as name in an input to get the value?
<script>
var k=0;
var counter = 50;
for(k=0; k<=counter; k++){
var choices = $('input[name=choices'+ k]).val();
var choices = choices.replace(/\ /g, '%');
var choices_ = choices_ +";"+ choices;
}
alert(choices);
</script>
there are multiple input field namely choices1,choices2 and so on.
how can i get the value of those fields using for loop?
how can i concatenate the name choices and the variable k?
can you help me solve this problem??
You could always just iterate using a specialized attribute selector and .each():
var choices = $('input[name^="choices"]'), // name starts with "choices"
choices_val = [] // an array!
;
choices.each(function () {
choices_val.push($(this).val().replace(/\ /g, '%'));
});
alert(choices_val.join(';'));
It saves you the overhead (and headache) of having to pick out and mangle a specific attribute value (choices1, choices2, etc) and having to select it out via selector ('cause I'd think that selecting via $(this) is faster than $('input[name="choices1"]')).
You're declaring choices three times, which is invalid and will lead to many errors.
You use each in jQuery, it's identical as for loop.
Say for example you have this HTML:
<input type ="text" name="field1" value="Alpha" />
<input type ="text" name="field2" value="Bravo" />
<input type ="text" name="field3" value="Charlie" />
And here is the js file:
var k = 1;
$('input').each(function(e) {
alert('choices' + k + '=' + $(this).val());
k++;
});
Demo here. Hope it helps.
$('input[name=choices'+ k +']').val();
you just forget to put another + sign and single quote.
I think you missed 2 quotes and a +.
$('input[name=choices' + k + ']').val();
add quotes
var choices = $('input[name=choices'+ k + ']').val();
use css selector
$(".className").each(function(){
$(this).myFunction();
})
jQuery.fn.myFunction = function()
var choices = $(this).val();
var choices = choices.replace(/\ /g, '%');
var choices_ = choices_ +";"+ choices;
}