Replace the value with "X" with same number of length - javascript

I have one input field with value : <input id="newfield" value="12345" />
Value of input can be vary and may contain the different length.
I want to replace the whole value if i click on button
<a href="#">button<a>
Value of id="newfield" is dynamic and input come from client side.
It may be 10 , 5 anything.
For example :
use type value - 123123456789
I want it like - xxxxxxxx6789
If user type value - 12345, I want it like - x2345
Note : open for jquery and js both

Convert value to string then loop based on length to replace each character with "X".
// input value "hello world"
var value = $("#input").val().split(""),
newVal = '';
for (var i = 0; i <= value.length - 4; i++) {
newVal += "X";
}
Based on your update, loop again through value array to add last 4 characters.
for (var i = value.length - 4; i <= value.length - 1; i++) {
newVal += value[i];
}
$("#input").val(newVal);
// new value "XXXXXXXXorld"
See it working.

jQuery
$('#mylink').click(function(){
var value = $("#newfield").val();
// make a string with x-characters
var x = new Array(value.length - 3).join('X');
// join this string with the tail of the value, and replace it
$('#newfield').val(x + value.substr(value.length - 4));
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input id="newfield" value="12345"/>
button
Vanilla JS
This uses the same internal code for altering the string, but doesn't use jQuery. Simply add the function to the link:
function changeInputValue() {
// get the value
var value = document.getElementById("newfield").value;
// make a string with x-characters
var x = new Array(value.length - 3).join('X');
// join this string with the tail of the value, and replace it
document.getElementById('newfield').value = x + value.substr(value.length - 4);
}
<input id="newfield" value="12345"/>
button

Assuming your button is:
button
if you are using jquery:
$("#button1").click( function()
{
var old_val = $(#newfield).val();
var last_part = old_val%10000;
var front_part = Array(old_val.length-4+1).join("X"); // to insert N Xs, we require `Array(N+1).join("X")`
$("#newfield").val(front_part + last_part) ;
});

<a href="#" onclick="getValueFromClient()">button<a>
<script>
function getValueFromClient(){
// write ajax call or something which will fetch value from client and assign back to input field.
var valueFromClient=10; // write code to fetch value
$("#newfield").val(valueFromClient);
}
</script>

Related

Auto increment value in element id

I am trying to get value of dynamic generated inputs. Here is my code and what I want actually
Here is my Code:
function activehead_standard(){
var cnt = 4;
for(i=1;i<=cnt;i++){
var active_head = document.getElementById('standard_'.i).value;
}
}
I want to get values of input:
standard_1
standard_2
standard_3
standard_4
but its not getting the value of input through ids I am sure its actually not getting the ids of inputs
use + for concatenation in javascript
function activehead_standard(){
var cnt = 4;
for(i=1;i<=cnt;i++){
var active_head = document.getElementById('standard_'+i).value;
}
}

My java script array doesn't have a length

I have the following code:
//Populate inputData with the values of the input text boxes, in order
var inputData = {};
var x = document.getElementById("newInventoryForm");
//Added this following line in the edit
$('#additionalContent').append("My x.length property " + x.length + "<br/>");
for (var i = 0; i < x.length - 1; i++) {// -1 so we don't get the submit button
var addData = {
id : x[i].id,
value : x[i].value
};
inputData[i] = addData;
$('#additionalContent').append(inputData[i].id + " : " + inputData[i].value + "<br/>");
}
I'm attempting to pass the form data from a previously made form to another javascript function. Before I do that I have tried to make it all work in the same .js page, however when I try to output my inputData through a for loop, it shows up blank. I determined this is because inputData.length is undefined. I was under the impression that declaring it as inputData = {}; made it an array and thus had a default length value. How can I change this to have the correct length?
Edit
Several commenters have said that var x = document.getElementById("newInventoryForm"); should return null or a node, neither of which has a length property. Adding the line in the code above, has produced this output.
My x.length property 18
serialNumber : 456
someDatafield : someInput
You've declared it as an object.
Perhaps var inputData = []; will give you better results.
{} is an object, not an array.
You want [].
Also, getElementById() does not return an array; your entire code makes no sense.

function to change argument to another sign

I dynamically create this list element and information a user has typed in shows up in it when a button is clicked 'info' is text and shuld show as it is but 'grade' is a number that i want to convert to another sign with the function changeNumber() but I am new to javascript and cant figure out how to make this function, can anyone give a suggestion or point me in the right direction?
var list = $("#filmlista");
var list_array = new Array();
function updateFilmList()
{
document.getElementById("name").value = '';
document.getElementById("star").value = 0;
var listan = list_array[0][0];
var grade = list_array[0][1];
var element = '<li class="lista">' + list + '<span class="grade">'+ changeNumber(grade) +'</span></li>';
list.append(element);
}
should I use innerHTML? not shure I understand how it works? and how do I use the replace method if I have to replace many different numbers to the amount of signs the number is?
for example if the number is 5 it should show up as: *****, if number is 3 show up as: *** and so on
Here's some code that should do the trick:
Add this function into your script.
function changeNumber(number) {
var finalProduct = "";
for (var i = 0; i < number; i++) {
finalProduct += "*";
}
return finalProduct;
}
Replace the updateFilmsList with this code.
document.getElementById("name").value = '';
document.getElementById("star").value = 0;
var listan = list_array[0][0];
var grade = changeNumber(list_array[0][1]);
var element = '<li class="lista">' + list + '<span class="grade">'+ grade +'</span></li>';
list.append(element);
It looks like you're trying to do something like PHP's str_repeat. In that case, take a look at str_repeat from PHPJS
There are options other than a loop:
function charString(n, c) {
n = n? ++n : 0;
return new Array(n).join(c);
}
charString(3, '*'); // ***
You can use innerHTML to set the text content of an element provided none of the text might be mistaken for markup. Otherwise, set the textContent (W3C compliant) or innerText (IE proprietary but widely implemented) property as appropriate.

How make jquery loop over with number

I am trying to assign a number to my variable i.e. colorswap1, colorswap 2, colorswap 3
I have the following
var i = 1-36;
// Get current image src
var curSrc = $('#colorswap'[i]).attr('src');
It doesn't seem to be putting the desired: colorswap1, colorswap2
Your variable declaration is doing the algebraic subtraction and will result in -35. You need a loop of some sort. Then, you concatenate the index with the string using the + operator. Because one of the things is a string, it will concatenate instead of "add".
Below is an example of what you can do:
for (var i = 1; i <= 36; i++) {
var curSrc = $('#colorswap' + i).attr('src');
// now do stuff with curSrc here
}

Javascript dynamic array of strings

Is there a way to create a dynamic array of strings on Javascript?
What I mean is, on a page the user can enter one number or thirty numbers, then he/she presses the OK button and the next page shows the array in the same order as it was entered, one element at a time.
Code is appreciated.
What I mean is, on a page the user can enter one number or thirty numbers, then he/she presses the OK button and the next page shows the array in the same order as it was entered, one element at a time.
Ok, so you need some user input first? There's a couple of methods of how to do that.
First is the prompt() function which displays a popup asking the user for some input.
Pros: easy. Cons: ugly, can't go back to edit easily.
Second is using html <input type="text"> fields.
Pros: can be styled, user can easily review and edit. Cons: a bit more coding needed.
For the prompt method, collecting your strings is a doddle:
var input = []; // initialise an empty array
var temp = '';
do {
temp = prompt("Enter a number. Press cancel or leave empty to finish.");
if (temp === "" || temp === null) {
break;
} else {
input.push(temp); // the array will dynamically grow
}
} while (1);
(Yeah it's not the prettiest loop, but it's late and I'm tired....)
The other method requires a bit more effort.
Put a single input field on the page.
Add an onfocus handler to it.
Check if there is another input element after this one, and if there is, check if it's empty.
If there is, don't do anything.
Otherwise, create a new input, put it after this one and apply the same handler to the new input.
When the user clicks OK, loop through all the <input>s on the page and store them into an array.
eg:
// if you put your dynamic text fields in a container it'll be easier to get them
var inputs = document.getElementById('inputArea').getElementsByTagName('input');
var input = [];
for (var i = 0, l = inputs.length; i < l; ++i) {
if (inputs[i].value.length) {
input.push(inputs[i].value);
}
}
After that, regardless of your method of collecting the input, you can print the numbers back on screen in a number of ways. A simple way would be like this:
var div = document.createElement('div');
for (var i = 0, l = input.length; i < l; ++i) {
div.innerHTML += input[i] + "<br />";
}
document.body.appendChild(div);
I've put this together so you can see it work at jsbin
Prompt method: http://jsbin.com/amefu
Inputs method: http://jsbin.com/iyoge
var junk=new Array();
junk.push('This is a string.');
Et cetera.
As far as I know, Javascript has dynamic arrays. You can add,delete and modify the elements on the fly.
var myArray = [1,2,3,4,5,6,7,8,9,10];
myArray.push(11);
document.writeln(myArray); // Gives 1,2,3,4,5,6,7,8,9,10,11
var myArray = [1,2,3,4,5,6,7,8,9,10];
var popped = myArray.pop();
document.writeln(myArray); // Gives 1,2,3,4,5,6,7,8,9
You can even add elements like
var myArray = new Array()
myArray[0] = 10
myArray[1] = 20
myArray[2] = 30
you can even change the values
myArray[2] = 40
Printing Order
If you want in the same order, this would suffice. Javascript prints the values in the order of key values. If you have inserted values in the array in monotonically increasing key values, then they will be printed in the same way unless you want to change the order.
Page Submission
If you are using JavaScript you don't even need to submit the values to the different page. You can even show the data on the same page by manipulating the DOM.
You can go with inserting data push, this is going to be doing in order
var arr = Array();
function arrAdd(value){
arr.push(value);
}
Here is an example. You enter a number (or whatever) in the textbox and press "add" to put it in the array. Then you press "show" to show the array items as elements.
<script type="text/javascript">
var arr = [];
function add() {
var inp = document.getElementById('num');
arr.push(inp.value);
inp.value = '';
}
function show() {
var html = '';
for (var i=0; i<arr.length; i++) {
html += '<div>' + arr[i] + '</div>';
}
var con = document.getElementById('container');
con.innerHTML = html;
}
</script>
<input type="text" id="num" />
<input type="button" onclick="add();" value="add" />
<br />
<input type="button" onclick="show();" value="show" />
<div id="container"></div>
The following code creates an Array object called myCars:
var myCars=new Array();
There are two ways of adding values to an array (you can add as many values as you need to define as many variables you require).
1:
var myCars=new Array();
myCars[0]="Saab";
myCars[1]="Volvo";
myCars[2]="BMW";
You could also pass an integer argument to control the array's size:
var myCars=new Array(3);
myCars[0]="Saab";
myCars[1]="Volvo";
myCars[2]="BMW";
2:
var myCars=new Array("Saab","Volvo","BMW");
Note: If you specify numbers or true/false values inside the array then the type of variables will be numeric or Boolean instead of string.
Access an Array
You can refer to a particular element in an array by referring to the name of the array and the index number. The index number starts at 0.
The following code line:
document.write(myCars[0]);
will result in the following output:
Saab
Modify Values in an Array
To modify a value in an existing array, just add a new value to the array with a specified index number:
myCars[0]="Opel";
Now, the following code line:
document.write(myCars[0]);
will result in the following output:
Opel
Please check http://jsfiddle.net/GEBrW/ for live test.
You can use similar method for dynamic arrays creation.
var i = 0;
var a = new Array();
a[i++] = i;
a[i++] = i;
a[i++] = i;
a[i++] = i;
a[i++] = i;
a[i++] = i;
a[i++] = i;
a[i++] = i;
The result:
a[0] = 1
a[1] = 2
a[2] = 3
a[3] = 4
a[4] = 5
a[5] = 6
a[6] = 7
a[7] = 8
Just initialize an array and push the element on the array.
It will automatic scale the array.
var a = [ ];
a.push('Some string'); console.log(a); // ['Some string']
a.push('another string'); console.log(a); // ['Some string', 'another string']
a.push('Some string'); console.log(a); // ['Some string', 'another string', 'Some string']

Categories

Resources