I have a ID with special characters. I need to get the value of this input with JQUERY.
<input style="text-align:center; width:50px;" type="text" onKeyPress="jq(this.id);" value="5" id="adhocGlobal_##HELLO DAVID%VSOP1240%6X0.7LFIG">
<script>
function jq(str) {
var id = str.replace(/[%#;&,\.\+\#*~':"!\^\$\[\]\(\)=>|\/\\]/g, '\\\\$&');
var value = $("#"+id).val();
alert(value);
}
</script>
I try with this, but i dont have response in the alert.
Help! please!
Normally you can use jQuery's escape sequence in a selector, \\, to escape special characters. However that won't work in this case as the id you have specified in the element is invalid as it contains spaces.
Due to that you will have to use the attribute selector in jQuery to retrieve it:
var $el = $('[id="adhocGlobal_##HELLO DAVID%VSOP1240%6X0.7LFIG"]');
console.log($el.val());
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input style="text-align: center; width: 50px;" type="text" onKeyPress="jq(this.id);" value="5" id="adhocGlobal_##HELLO DAVID%VSOP1240%6X0.7LFIG">
A much better solution would be to fix the id of your elements before they are output in to the page to remove the spaces and special characters.
Get the answer from fiddle here
I have written in both javascript & jquery. There is an option fot trying // before every special character in ID, but that doesn't worked for me. So on the other way you can get the answer. Check & let me know.
$("#clickID").on('click', function(){
getVal = $(document.getElementById('adhocGlobal_##HELLO DAVID%VSOP1240%6X0.7LFIG')).val();
console.log(getVal);
alert(getVal);
});
function jq(str) {
var element = document.getElementById("adhocGlobal_##HELLO DAVID%VSOP1240%6X0.7LFIG");
var value = $(element).val();
alert(value);
}
Related
I have a simple calculator on ASP.NET MVC5, front side is on HTML\CSS\Javascript.
In event handlers for buttons I concatenate all values into a string and want to check if it satisfies the regex. But, for example, if I put following values into my calculator: '99*66-', the code below returns null every time.
Here regex works okay: https://regex101.com/r/AxMvPe/1
Whole code: https://jsfiddle.net/0g79hkbc/
var regEx = /[+-]?([0-9]*[,])?[0-9]+[-+\/*][0-9]*[,]?[0-9]+[-+\/*]/; //in case if problems will appear https://regex101.com/
$('.button').on('click', function () {
var buttonText = this.innerHTML;
var inputedText = inputElement.innerHTML + buttonText;
console.log(inputedText.match(regEx));
});
I have tried following options, but they didn't help:
to replace regex expression on Regex object
to use .test() instead of .match() (got false)
to use .search() instead of .match() (got -1)
I also tried to manually entered '99*66-' and then compare inputedText with javascript string '99*66-', it also returns false. Why?
Looks good to me, except that it will not match when there is for example 99*. You will need a repeating set of regex like: https://regex101.com/r/AxMvPe/2
Added floats to it :)
var regEx = /[+-]?([0-9]*[,])?[0-9]+[-+\/*][0-9]*[,]?[0-9]+[-+\/*]/; //in case if problems will appear
inputElement = $('#input');
$('.button').on('click', function () {
var buttonText = $(this).val();
var inputedText = inputElement.val() + buttonText;
console.log(inputedText.match(regEx));
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<input id='input' type='text' value='99*66' />
<input class='button' type='button' value='-'/>
I'm trying to put together multiple user inputs and then combine them into one textarea after button click.
For example:
User1:Hey, I just met you
User2:And this is crazy
User3:But Here's my number so call me maybe
Combined Result:
Hey, I just met you, And this is crazy, But Here's my number so call me maybe
Here's my code the button click is currently not working but when I tried it before it did work so I was thinking I have some problem w/ my Jquery that triggers this unusual result:
HTML and Imports:
<script src="//ajax.googleapis.com/ajax/libs/jquery/1.10.2/jquery.min.js"></script>
<input class="combine" id="input1" disabled="true"></input>
<input class="combine" id="input2" disabled="true"></input>
<input class="combine" id="input3" disabled="true"></input>
<input class="combine" id="input4" disabled="true"></input>
<input class="combine" id="input5" disabled="true"></input>
<input class="combine" id="input6" disabled="true"></input>
<input class="combine" id="Voltes5" disabled="true" size="45"></input>
<button id="setVal">Set</button>
Jquery
$(document).ready(function(){
$('#setVal').on('click',function(){
jQuery(function(){
var form = $('.combine');
form.each(function(){
$('.Voltes5').append($(this).text()+ ' ');
});
});
});
});
Update for sir Arun P Johny
User1: If theres a (no comma when combined)
User2: will
User3: there's a way
Combined Result:
If theres a will, there's a way
Try
$(document).ready(function () {
$('#setVal').on('click', function () {
var form = $('.combine').not('#Voltes5');
var vals = form.map(function () {
var value = $.trim(this.value)
return value ? value : undefined;
}).get();
$('#Voltes5').val(vals.join(', '))
});
});
Demo: Fiddle
Here's a one-liner for non-readability ;)
$('#setVal').click(function(){$('#Voltes5').val($('.combine').not('#Voltes5').map(function(){return $(this).val();}).get().join(''))});
Expanded:
$('#setVal').click(function(){
$('#Voltes5').val(
$('.combine')
.not('#Voltes5')
.map(
function(){
return $(this).val();
})
.get()
.join('')
);
});
Get fiddly with it: http://jsfiddle.net/ArtBIT/u57Zp/
Here is one way to do this:
$('#setVal').on('click', function () {
$(".combine[id^=input]").each(function () {
if(this.value) {
$("#Voltes5")[0].value += ' ' + this.value;
}
});
});
There are several different ways to do this..
I'd do it this way using an array:
$(document).ready(function () {
$('#setVal').on('click', function () {
//create an array for the values
var inpAry = [];
$('.combine').each(function () {
//add each value to the array
inpAry.push($(this).val+' ');
});
//set the final input val
$('#Voltes5').val(inpAry);
});
});
but you would need to remove the combine class from #setVal because that would be included in the .each.
This way it would also be possible to have the final box updated on keyup as I'm not just appending the values, the combined values are set each time.
$(document).ready(function(){
$('#setVal').on('click',function(){
var val='';
$('.combine').not('#Voltes5').each(function(){
val+=$(this).val();
});
$('#Voltes5').val(val);
});
});
.text() will give text of the element ,for input val u have to use .val()
So there's immediate big problem in the code, which is that you're referring to your Voltes5 element as a class, not an ID. The jQuery selector you want is:
#Voltes5
instead of:
.Voltes5
There are a few other things to think about too, though, for the sake of functionality and best practices. Firstly, the Voltes5 element also has class combine, meaning that the $('.combine').each() call will include this element. The outcome of this is that it will also append its current text to itself when the code is run (or, when the code is run with the above correction).
When grabbing the current entered text of an input element, a jQuery .val() call is what you want, not .text() - see this answer for some more discussion.
Another thing that could be noted is that you should really explicitly specify what sort of input these elements are; <input type="text"> is hugely preferable to <input>.
Finally, input is a void element (reading), meaning it shouldn't have any content between opening and closing tags. Ideally, you wouldn't even give a closing tag; either have just the opening tag, or self-close it:
<input>
<input />
HTH
replace $('.Voltes5').append($(this).text()+ ' ');
with
$('#Voltes5').append($(this).text()+ ' ');
I have a some text boxe with id that contains special character like '(' and ')' . when i am accessing value of this text boxe i am getting value as undefined .need solution of this problem ...
<input type="text" id="header_COUNT(SUBJECT)" onblur="javascript:setHeader();" disabled="disabled">
script is
function setHeader(){
var val=$('#header_COUNT(SUBJECT)').val();
console.log(val);
}
This is not such a complex selector. You can use getElementById:
var val=$(document.getElementById('header_COUNT(SUBJECT)')).val();
You can escape characters in jQuery with 2 backslashes \\
So reference it like:
$('#header_COUNT\\(SUBJECT\\)')
jsFiddle
Use the following code
function setHeader(){
var val=$('input[id="header_COUNT(SUBJECT)"]').val();
console.log(val);
}
jsbin
var id_with_special_chars = 'header_COUNT(SUBJECT)';
var value = $('input[id="'+id_with_special_chars+'"]').val();
alert(value);
So basically here is my jsFiddle - http://jsfiddle.net/CmNFu/ .
And code also here -
HTML -
<b style="float: left; margin-right: 10px;">category 1</b><input type="checkbox" value="category1" style="float: left;" class="portfolio-category" /><br />
<b style="float: left; margin-right: 10px;">category 2</b><input type="checkbox" value="category2" style="float: left;" class="portfolio-category" /><br />
<br />
<br />
<input type="text" name="categories" id="portfolio-categories" />
jQuery -
jQuery(document).ready(function() {
jQuery(".portfolio-category").click(function() {
if(jQuery(this).is(":checked")) {
jQuery("#portfolio-categories").val(jQuery("#portfolio-categories").val()+" "+jQuery(this).val());
}
else {
var portfolioCategories = jQuery("#portfolio-categories").val();
alert("before + "+portfolioCategories);
var currentElement = jQuery(this).val()+" ";
alert(currentElement);
portfolioCategories = portfolioCategories.replace(currentElement, "");
alert(portfolioCategories);
}
});
});
Well basically what I would like to achieve is, when user checks the checkbox, the value automatically adds inside input field (Done, it's working, whooray!), but the problem is when it unchecks the checkbox, the value should be removed from input box (the problem starts here), it doesn't remove anything. You can see I tried assigning val() function to variables, but also without success. Check my example on jsFiddle to see it live.
Any suggestions? I guess replace() is not working for val(), is it?
So, is there any other suggestions?
I'd do this:
jQuery(document).ready(function() {
jQuery(".portfolio-category").on('change', function() {
var string = "";
$('input[type="checkbox"]').each(function() {
var space = string.length>0?' ':'';
string += this.checked?space+this.value:'';
});
$("#portfolio-categories").val(string);
});
});
FIDDLE
You have quite the issue with spaces in that input box. but we'll get to that in a moment.
first, this will kind of work (if it weren't for the spaces problem):
add this line before the last alert:
jQuery("#portfolio-categories").val(portfolioCategories);
this will work, but not always, as the last element you append doesn't have a space after it.
but if you change the 4th line to this:
jQuery("#portfolio-categories").val(jQuery("#portfolio-categories").val()+jQuery(this).val()+" ");
it will work, as it adds the space after each element, instead of before.
http://jsfiddle.net/CmNFu/5/
your issue was that you changed the values in the variable: portfolioCategories, but you haven't updated the input itself. (notice, changing the value of a string, doesn't change the value of the input it originally came from)
What you need is to insert back the string portfolioCategories into the input. Also the spaces are creating a lot of problems. You could use $.trim(str) to remove any leading and trailing spaces from a string.
Have updated your fiddle with a solution that works.
http://jsfiddle.net/CmNFu/11/
Hope this helps.
HTML:
<input type="text" id="priceperperson1" name="priceperperson1" />
<input type="text" name="personsvalue1" class="countme" readonly="readonly" />
JS:
jQuery(document).ready(function($) {
$('div.pricerow input.countme').each(function(){
var id = this.name.substr(this.name.length-1);
alert($('input#priceperperson'+id));
this.value = parseInt($('priceperperson'+id).value) * parseInt($('countpersons'+id).value);
});
});
Shortened as possible. All I've in alert is "Object"... Value is NaN. I've tried to "parseInt" on id. I've tried:
$('[name=priceperperson'+id+']');
$('priceperperson'+id);
What I'm doing wrong?
You are retrieving jQuery objects when you do the $(..)
To get the value (string) use the .val() method.
so
alert( $('input#priceperperson'+id).val() );
You should probably put the $ in the function definition.
I'm guessing it's causing the $ variable to be re-defined, in the function -- and not point to the jQuery's $() function anymore.
I'm thinking about this one :
jQuery(document).ready(function($) {
Try using, instead :
jQuery(document).ready(function() {
When you are looping through jquery objects, I believe you have to use:
$(this).attr('name'); instead of this.name
also, to call values from objects you have to use $.val() or $.attr('attributename');
// Shortcut for doc ready
$(function()
{
// Loop through values
var id = $(this).attr('name');
alert($('input#priceperperson' + id).val());
});
Are you perhaps looking for .val()?
this.val(parseInt($('priceperperson'+id).val()));
All I've in alert is "Object"... Value
is NaN. I've tried to "parseInt"
Try giving a base to parseInt:
parseInt(variable, 10);
There are some mistakes... to get the value of a jQuery object you must use .val() method, not .value.
Then, the parseInt() requires, as second parameter, the radix. Something like:
...
this.value = parseInt($('priceperperson'+id).val(), 10) * parseInt($('countpersons'+id).val(), 10);
...
your code may contain errors
your code
id = lenght 1 OK
if id lenght > 1 ?? possible exception
priceperperson1 to priceperperson_1
# option # proposal
<input type="text" id="priceperperson_1" name="priceperperson_1" /> // => use "_"
<input type="text" name="personsvalue_1" class="countme" readonly="readonly" />
jQuery(document).ready(function($) {
$('div.pricerow input.countme').each(function(){
var id = this.name.split("_")[1]; // => get array value
this.value = parseInt($('[name=priceperperson_'+id+']').value()) *parseInt($('[name=countpersons='+id+']').value());
});
});