JavaScript ID tag selection - javascript

Is there a better way to write jQuery('#'+ myId) in JavaScript.
I have an ID in a variable without the # character and jQuery('#'+ myId) looks ugly.
var myId = 'last-element-id';
jQuery('#'+ myId)
I'd like to avoid the + character to join the strings.
Thanks

But, have in mind that returned element is not a jQuery collection
function getElement(element) {
return document.getElementById(element)
}

function jQueryID(myId){
return jQuery('#'+ myId);
}
and then call like
jQueryId(myId);

As simple as that:
var myId = '#last-element-id';
jQuery(myId);
or
var myId = '#' + 'last-element-id'; // if 'last-element-id' is dynamically generated value
jQuery(myId);

I think when you are using jQuery, is better you stick with jQuery in all your code.
My offer is, create a function as below:
var getId = function(id){
return '#'+ id;
}
and call that anywhere you need, and stick with jQuery. like this:
$(getId(id));

Related

How to use concatenation with a variable used in a JavaScript JQuery function

I'm trying to use a variable that contains the name of a HTML element in a JQuery function for a radio button.
Normally I would do something like this:
var oldRadioValue = $('input[name="correct10")"]:checked').val();
But due to the radio button being created dynamically I need to do something like this:
var radioName = "correct"+questionCount;
var oldRadioValue = $('input[name=radioName]:checked').val();
When I check the console.log() I am getting undefined...
Thanks in advance for any help!
You should be able to it like this do this
var oldRadioValue = $('input[name="' + radioName + '"]:checked').val();
You can either use concatenation like this:
var oldRadioValue = $('input[name="'+radioName+'"]:checked').val()
Or the newer template literal syntax:
var oldRadioValue = $(`input[name="${radioName}"]:checked`).val();
Your need string concatenation to make this work.
var oldRadioValue = $('input[name=' + radioName + ']:checked').val();

Replace different Values in String?

I have a string which looks like this: (id:561644cdb40fbe0100247dd7:q) (id:56165d8a79c8c40100adbdb6:q) and I need to replace the different id's with different values. I already have the id's in a variable and trying to loop through with something like this var mailId = "(id:" + rplcId + ":q)"; But If I use the replace() function it doesnt work...Any other suggestions?
You can select the id with:
"(id:56165d8a79c8c40100adbdb6:q)".split(":")[1]
var id = "(id:561644cdb40fbe0100247dd7:q)";
var idArr = id.split(":");
idArr[1] = newId; //56165d8a79c8c40100adbdb6
var mailId = idArr[0]+idArr[1]+idArr[2];
and please provide your full code

Get only word part of an id/name

I have a div element with lots of descendent's elements, all with ids in the form "word1", for a simple example: id="moviment1" or id="type1".
I need to get only the written part of these ids (moviment or type), in order to concatenate their names with a increment of 1 (id="moviment2" or id="type2").
$clone.find('*').each(function() {
var id = $(this).prop('id');
var num = parseInt( $(this).prop("id").match(/\d+/g), 10 ) +1;
$(this).prop('id', id+num);
});
The way it is, I always get ids like id="moviment12". I already tried:
var id = $(this).prop('id').replace(/\d+/g, '');
or
var id = $(this).prop('id').match(/\w+/);
But I always get errors like "cannot read property 'replace'/'match' of undefined". So, what am I doing wrong? Any other ideas? Thank you very much!
Ideally you should use a template. Traversing and modifying parsed elements makes your code slow and hard to maintain.
If you want to increment the number part of the IDs by 1 you can use the replace method callback function:
$clone.find('[id]').prop('id', function(_, id) {
// Assuming `id` is `test_25_segment`
return id.replace(/(\d+)/, function(num) {
// |
// --- is 25
return +num + 1;
// |
// --- parses the matching string into integer
});
});
Here is a demo using the above snippet.
Easiest way, you could just add those values as data-attr:
<div id="type1" data-id="1" data-text="type"></div>
So you can easily get them separated just using .data('id') and .data('text').
You may select the elements by this way:
var all = [].filter.call(document.querySelectorAll('[id*=type]'), function(el) {
return (/\btype\d+\b/).test(el.id);
});
and then you can change the ids using methods like replace()
Try this...
var onlyAlphabets = id.split(/(\d)/)[0];

Get content of tag value using Javascript

i want know how i can retrieve the content of an HTML inner tag value for a specific ID, for example:
<span id="mycount" value="100">1</span>
i want retrieve the 100 value, i have tried this:
var num = document.getElementById('mycount').value;
i have also tried this:
var anchors = document.getElementById('mycount');
var num = anchors.value();
but doesn't work, how i can do it?
using jquery:
var num = $("#mycount").attr("value");
jQuery.attr()
Tag span can't have value property, it's not valid. Yes, it works, but it's a bad practice. Instead, you can use valid HTML5 attribute data-*.
In your case, that will be:
<span id="mycount" data-value="100">1</span>
and jQuery code to get this data value with .data() function is:
$(document).ready(function(){
var myvalue = $('#mycount').data('value');
alert(myvalue);
});
DEMO: http://jsfiddle.net/KhmGL/
var num = document.getElementById('mycount').getAttribute('value');
Take a look # MDN element.getAttribute.
to get attribute values we have to use getAttribute().
to get the value of mycount
var mycount = document.getElementById("mycount");
var num = mycount.getAttribute("value");
alert(num);

JQuery: How to get name of a select when value is known?

I need to get the name of a select (#Dropdown) when its value is known but can't seem to get the syntax right. Here's an example:
$(document).ready(function()
{
var countrycode = '55';
var name = $("#Dropdown[value=countrycode]").text(); // fails here
if(name == 'Germany')
{..... etc
I can get it to work as follows in a different context when I'm able to use "this":
var name = $(this[value=countrycode]).text();
... but that's not available in the first example.
Anyone? Thanks.
You need to look for the option value within the select.
var countrycode = '55';
var name = $("#Dropdown option[value="+countrycode+"]").text();
You're including "countrycode" literally in your selector string.
There's probably a better way to do it, but this should work:
var name = $("#Dropdown[value=" + countrycode + "]").text();
Post also HTML, it seems kind of wrong - you can have just one ID (#something) per page, so there would be no need for something like #id[value=*].
try:
var name = $("#Dropdown option[value=" + countrycode + "]").text()

Categories

Resources