Can't capitalize first letter, element not updated - javascript

I am getting my string from a textBox like this (in a loop where index is incremented):
var name = document.getElementById("TextBox" + index).value;
And I have a function in my script that looks like this meant to uppercase first letter:
function capital(string)
{
return string.charAt(0).toUpperCase() + string.slice(1);
}
And try to use it like this:
var name = document.getElementById("TextBox" + index).value;
capital(name);
They are in different functions in the same script tag. Where am I going wrong?

Make sure you assign the modified value back to the control:
var element = document.getElementById("TextBox" + index);
var name = element.value;
element.value = capital(name);

Are you trying to getElementById using the input type, or do you have actual IDs on your textbox called 'TextBox'? The below works fine, see fiddle
var index = 1;
var name = document.getElementById("test" + index).value;
function capital(str)
{
return str.charAt(0).toUpperCase() + str.slice(1);
}
alert(capital(name));

String are immutable in js, you need to reassign.
var name = capital(document.getElementById("TextBox" + index).value);
Plus strings are passed by value, so they are copied over to the new function. So whatever you do in the function won't cause any effects in your name variable.

Related

how to replace class name dynamically in javascript

I want to change a class dynamically and append a counter to the end of it. I wrote this code but it is treated like strings.
This is the code:
var divClass = document.getElementById('div2');
var i = 1;
setInterval(function () {
divClass.className=divClass.className.replace('color','color'+ i);
i++;
},5000);
how can i fix this issue?
I think the issue is that after the first loop the class name will be color1 and your replacing only the "color" part so you end up with color12 You could just set className since that overrides the previous one
divClass.className = 'color'+ i;
if you had classes before you can store them and them first so you don't override them : var classes = divClass.className;
and when you set them divClass.className = classes + ', color'+ i;
You could use the classList feature that is in JavaScript like this:
var divClass = document.getElementById('div2');
var i = 1;
setInterval(function () {
divClass.classList.remove('color' + (i - 1));
divClass.classList.add('color' + i++);
}, 5000);
Your numbers are more than likely getting treated as a string because you are concatenating with a string. By placing items within parentheses, they will be executed as numbers (because anything in parentheses get run first) then concatenated as a string.
Use instead:
element.className = 'other const clases' + 'color'+ i;
You have to change full string of class or change it in 2 steps with for example regex and then assign it again.

how to remove particular substring from string using id of li in jquery

I have string
0=>zxz##5=>zxzx##5=>zxz##10=>zxz##1=>asdasd##12=>asdsad##10=>asdsad
where 0,5,10 are ids, text are values and ## is delimiter.
I have id and i want to remove id's value
This is my following code, Please check and suggest.
code1
function remove_feature(id)
{
var feature_str = $("#features_post").val();
var feature_string = feature_str.replace(['id=feature_str'],'', 'gi');
window.jQuery("#features_post").val(feature_string);
window.jQuery("#"+id+"").remove();
alert(feature_string);
return true;
}
code2
function remove_feature(id)
{
var feature_str = $("#features_post").val();
var feature_string = feature_str.replace(id,'', 'gi');
window.jQuery("#features_post").val(feature_string);
window.jQuery("#"+id+"").remove();
alert(feature_string);
return true;
}
I have tried both of code but not working
Try this one with jquery : http://jsfiddle.net/h0qtxn7d/
Can also remove same multiple ids.
var k = "0=>zxz##5=>zxzx##5=>zxz##10=>zxz##1=>asdasd##12=>asdsad##10=>asdsad";
var obj = k.split("##");
var removeItem = 5;
alert('Array before removing the element = ' + obj)
obj = jQuery.grep(obj, function(value) {
return value.split('=>')[0] != removeItem;
});
alert('Array after removing the element = ' + obj);
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
Misread the question, sorry.
To replace each key => value pair within that string you could use regular expressions:
var string = "0=>zxz##5=>zxzx##5=>zxz##10=>zxz##1=>asdasd##12=>asdsad##10=>asdsad";
function remove_feature(id) {
var x = new RegExp("" + id + "\=>[a-z0-9]+(##)?", "gi")
return string.replace(x, "");
}
So, remove_feature(5) prints "0=>zxz######10=>zxz##1=>asdasd##12=>asdsad##10=>asdsad".
If the id parameter is a key which exists in your provided string and the respective name should be returned you could make use of the JSON.parse function pretending to parse a url. Therefore you could replace the delimiters by &s and the => by =s:
var string = "foo=>bar##john=>doe";
function remove_feature(id) {
// id should be something left hand side the =>, like 0 or 1
var _string = string.replace('##', '&').replace('=>', '='),
obj = JSON.parse('{"' + decodeURI(_string).replace(/"/g, '\\"').replace(/&/g, '","').replace(/=/g,'":"') + '"}'),
_id = obj["" + id];
$('#' + _id).remove();
}
Usage: remove_feature("foo") would remove an element with id #bar.

Select Part of a Attribute - JQuery

I need to get the number only from an attribute (The number is dynamic). The button/anchor looks like this:
Delete Dish
The part I need to dissect is this bit 'bc_inventorybundle_menu_product_0' I only want the number, for use in another function (Delete a LI with an ID of menuitem0_dish)
The code I use for selecting ID's elsewhere is:
function getNum(element, attrPrefix) {
//set prefix, get number
var prefix = attrPrefix;
var num = element.attr("id").substring((prefix.length));
return num;
}
It works great on ID's but I cant seem to get it to work for Attributes instead of ID's
So User clicks delete button bc_inventorybundle_menu_product_0 then jQuery removes the < li id="menuitem0_dish">
I can't add an ID to the button so I have to use the attribute of the button. As I'm sure you can tell I'm a complete noob when it comes to JS/JQuery.
EDIT
Having read all the answers I feel I may need to elaborate a little.
I think the biggest issue is registering when the Button/Anchor is clicked.
What I currently have is this, which I know must be wrong:
$(document).on('click', 'data("field")', function(event) {
deleteDish(this);
});
function getbutNum(element, attrPrefix) {
//set prefix, get number
var prefix = attrPrefix;
var butnum = element.data("field").substring(prefix.length); //Changed as per suggestions
return butnum;
}
function deleteDish(field) {
var numbut = getbutNum();
//Delete the UL/LI
console.log("Num But" + numbut);
}
Asides from all else this gives me an error of 'unrecognized expression: data("field")'
Have you tried selecting your actual data attribute:
var num = element.attr("data-field").substring(prefix.length);
Or:
var num = element.data("field").substring(prefix.length);
EDIT
First add a class to your anchor element (I'm going under the assumption that you have more than one of these):
Delete Dish
Then:
$(".delete-dish").on("click", function (e) {
e.preventDefault();
var fieldData = $(this).data("field"),
num = fieldData.substring(fieldData.lastIndexOf("_") + 1);
console.log("Num But" + num);
});
Here is a fiddle to demonstrate
Using the attribute name that contains your input should work:
function getNum(element, attrPrefix) {
//set prefix, get number
var prefix = attrPrefix;
var num = element.attr("data-field").substring((prefix.length));
return num;
}
http://jsfiddle.net/zf3hmo4q/
Considering you want to parse attributes with "data-*" name:
function getNum(element, dataName, dataPrefix) {
var num = element.data(dataName).replace(dataPrefix, "");
return num;
}
console.log(getNum($(".btn"), "field", "bc_inventorybundle_menu_product_"));
Maybe something like this?
var getNumberFromAttribute = function(id, field) {
var field = $(id).data(field);
var parts = field.split("_");
return parts[parts.length - 1]
}
Here's a jsfiddle http://jsfiddle.net/o6go79cL/
UPDATE
You could just pass in the element. The only purpose of the id was to select the object. So you could also just do:
var getNumberFromAttribute = function(elm, field) {
var field = $(elm).data(field);
var parts = field.split("_");
return parts[parts.length - 1]
}
number = getNumberFromAttribute(anchorTag, "field");

String append from <select> to form new variable

I have a combobox in HTML:
<select id="dimensionName"><option>/Example.html</option></select>.
In my JavaScript, if I have a var URL1 = "facebook.com", and I want to append the selected string from the above combobox to the end of URL1, and set the appended string as a new variable as NewDimensionName, how can I do that?
I tried doing the following but to no avail:
var NewDimensionName = URL1.concat(document.getElementById("dimensionName").selectedItem);
Since you want to get the text, you would have to do it like this:
var x = document.getElementById("dimensionName");
var NewDimensionName = URL1+x.options[x.selectedIndex].text;
This gets the options array with the selected index and returns the text, not the value.
Also note that concat() is used for arrays, not strings. Simply using + will suffice here.
Can you try this,
var dimensionName= document.getElementById("dimensionName");
var dimensionText= dimensionName.options[dimensionName.selectedIndex].text;
var NewDimensionName = URL1 + dimensionText;
console.log("NewDimensionName ::" + NewDimensionName );
x = document.getElementById("dimensionName").options[dimensionName.selectedIndex].innerHTML;
x = URL1 + x;
alert x;

Save and print list with array

I need help print and save element in an array in javascript. I know that I have to create an array, and then use a for-loop to save and print it, but i don't know how. What i want to do i so make a simple currency converter, use a for-loop with an array to save the converted input and display it. Here is my code:
JAVASCRIPT
var input = document.querySelector("#input");
var convert = document.querySelector("#convert");
var dollar = 0.51;
var euro = 0.11;
omvandla.onclick = function (){
if(isNaN(input.value)){
alert ("Use numbers");
}
else{
console.log(("Dollar:" + input.value*dollar) + ("Euro:" + input.value*euro));
}
};
HTML
<p>
<form>
<label>Kronor: <input type="text" id="kronor"/></label>
<br><input type="submit" id="convert" value="Omvandla"/>
</from>
</p>
How can I append the converted value after the submit button?
If you want to display one Conversion Result after another, you could do this like this:
var input = document.querySelector("#kronor");
var convert = document.querySelector("#convert");
var dollar = 0.51;
var euro = 0.11;
var conversionArray = [];
convert.onclick = function (){
if(isNaN(input.value)){
alert ("Use numbers");
}
else{
var dollarResult = input.value*dollar;
var euroResult = input.value*euro;
var newArrayEl = {
dollar: dollarResult,
euro: euroResult
};
conversionArray.push(newArrayEl);
console.log(conversionArray);
document.getElementById("convertedValue").innerHTML = "Dollar: " + dollarResult + " Euro: " + euroResult + "<br>" + document.getElementById("convertedValue").innerHTML;
}
};
Then you can access single values of the conversion by e.g. conversionArray[indexOfElement].dollar
This way you don't need an array to store the values. If you really need thos wvalues again, let me know, and im showing you how to store the array.
Here is a Fiddle, that shows how it works.
In javascript the way you add elements to an array is the push function
var myArray = [];
myArray.push(15);
Then to loop through the elements you can do something like this
for(var elem in myArray){
//Do something with elem
}
From your problem description it is hard to figure out what you are trying to do with your code. Hopefully this will help with array manipulation
You can add an element to the end of an array by using the array.push() function. I your example you would do something like:
array = [];
...
omvandla.onclick = function (){
if(isNaN(input.value)){
alert ("Use numbers");
}
else{
console.log(...);
array.push(input.value);
}
};
For more information about JavaScript arrays see here.

Categories

Resources