Replace all occurrences of "<", ">" inside value attribute - javascript

I have the requirement to replace all occurrences of "<" and ">" characters that are found inside the value attribute. I want to replace "<" and ">" characters with ""
This is my sample html:
<form name="form1">
<input type="text" value="<first set><second set><third set>" />
<input type="text" value="<fourth set><fifth set><sixth set>" />
</form>
I tried using javascript replace method but no luck.

You could use this pure JavaScript function:
function removeLessGreaterThan(html) {
// Use the DOM API to change the value attribute values:
var span = document.createElement('span');
span.innerHTML = html;
var inputs = span.querySelectorAll('input[type=text]');
for (var i = 0; i < inputs.length; i++) {
inputs[i].setAttribute('value', inputs[i].value.replace(/[<>]/g, ''));
}
return span.innerHTML;
}
// Sample data:
var html = '<form name="form1"> <input type="text" value="Here is a >test<." /> <input type="text" value="And another >test<." /> </form>';
html = removeLessGreaterThan(html);
console.log(html);

const FORM_NAME = "form1";
var fields = document.getElementsByName(FORM_NAME)[0].getElementsByTagName("input");
for(var i = 0; i < fields.length; i++) {
fields[i].value = fields[i].value.replace(/[<>]/g, "");
}

I think you are expecting this way. Please go through the code.
function ReplaceMyValues()
{
var inputs = document.getElementsByTagName('input');
for (var i = 0; i < inputs.length; i += 1) {
if(inputs[i].type=="text")
{
var currentValue=inputs[i].value.replace(/[<>]/g, "");
inputs[i].value = currentValue;
}
}
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.10.1/jquery.min.js"></script>
<form name="form1"> <input type="text" value="<first set><second set><third set>" /> <input type="text" value="<fourth set><fifth set><sixth set>" />
<input id="Test" type="button" value="Replace" onclick="ReplaceMyValues();"></input>
</form>

You can use jquery
$(".yourInput").val($(".yourInput").val().replace('<', '').replace('>', ''))

Related

How to accept the input from a text box and display in array format in jQuery?

I have written the code of taking input value from a text box and adding it to an array using the add button and also displaying the values of the array when the display button is clicked.
The thing is I did all this using JavaScript and now I want to do it using jQuery. I tried a code snippet from this website but it's not working. Please help.
<body>
<script src="jquery-3.3.1.js"></script>
<input type="text" id="text1"></input>
<input type="button" id="button1" value="Add" onclick="add_element_to_array();"></input>
<input type="button" id="button2" value="Display" onclick="display_array();"></input>
<div id="Result"></div>
<script>
var x = 0;
var sample = []; // <-- Define sample variable here
function add_element_to_array(){
$(document).on('click', '#btnSubmit', function () {
var test = $("input[name*='i_name']");
$(test).each(function (i, item) {
sample.push($(item).val());
});
console.log(sample.join(", "));
});
}
function display_array() {
var e = "<hr/>";
for (var y = 0; y < sample.length; y++) {
e += "Element " + y + " = " + sample[y] + "<br/>";
}
document.getElementById("Result").innerHTML = e;
}
</script>
</body>
You can use this code to get idea of how it should work. You can also check for non-empty value before pushing the value into the array as an empty value in array will not make any sense.
$(document).ready(function(){
var valueArray = [];
//add value in array
$('#button1').click(function(){
var textValue = $('#text1').val();
//push non empty value only
if(textValue.trim() !== ''){
valueArray.push(textValue);
//reset the text value
$('#text1').val('');
}
});
//display value
$('#button2').click(function(){
$('#Result').html(valueArray.toString());
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input type="text" id="text1"></input>
<input type="button" id="button1" value="Add"></input>
<input type="button" id="button2" value="Display"></input>
<div id="Result"></div>
I have added the jquery script considering the following as your suggested html.
<input type="text" id="text1"></input>
<input type="button" id="button1" value="Add"></input>
<input type="button" id="button2" value="Display"></input>
<div id="Result"></div>
The inptArr must be a global array.
<script>
var inptArr = [];
$('#button1').on('click',function(){
if($('#text1').val() != '')
inptArr.push($('#text1').val());
});
$('#button2').on('click',function(){
var string = '';
var lastIndex = parseInt(inptArr.length - 1);
for(var i = 0; i <= lastIndex ; i++)
{
if(i == lastIndex)
string += inptArr[i];
else
string += inptArr[i] + ',';
}
$('#Result').append(string);
});
</script>
This is another way to achieve what you want with minor changes.
You have only one text input element so don't need any each loop.
document.ready() is needed if you define script from starting of the code because at starting there is no defined element that have an id as btnSubmit so this block must wait to dom elements to be ready.
Also you don't need pure javascript code getElementById on display_array() function when you use jquery. You can change it as $("#Result").html(e);
var x = 0;
var array = [];
$(document).ready(function(){
$('#btnSubmit').on('click', function () {
array.push($("#text1").val());
});
});
function display_array() {
var e = "<hr/>";
for (var y = 0; y < array.length; y++) {
e += "Element " + y + " = " + array[y] + "<br/>";
}
$("#Result").html(e);
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input type="text" id="text1"/>
<input type="button" id="btnSubmit" value="Add"/>
<input type="button" id="button2" value="Display" onclick="display_array();"/>
<div id="Result"></div>
In your code functions passed to onclick attributes are binding the click event to a DOM - don't do that.
var array = Array();
var input = $("#text1");
var result = $("#result");
function add_element_to_array(){
var value = input.val();
array.push(value);
console.log("Add:", value);
// input.val(""); // bonus: clears input after adding text to an array
}
function display_array() {
result.text(array.toString());
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input type="text" id="text1">
<input type="button" id="button1" value="Add" onclick="add_element_to_array();">
<input type="button" id="button2" value="Display" onclick="display_array();">
<div id="result"></div>

Make a button submittable more than once

So I found a script that can generate your link when you want to, here it is (credits to the owner!)
function CreateAffiliateLink(F) {
var findstring = "XXXXX";
var ts = 'var replacewith=document.' + F.name + '.AffCode.value';
eval(ts);
if (replacewith.length < 1) {
return;
}
var re = new RegExp(findstring, "g")
for (i = 0; i < F.length; i++) {
var s = new String(F.elements[i].value);
if (s.length > 0) {
var newstr = s.replace(re, replacewith);
F.elements[i].value = newstr;
}
}
}
<form name="me">
<p>
Type your affiliate code in the box and click the button:
<input type="text" name="AffCode" size="17">
<input type="button" value="Personalize links with my affiliate code" onClick="CreateAffiliateLink(this.form)">
</p>
<p>
Image link:<br>
<textarea name="a" cols="46" rows="3" wrap="off">
<a href="http://example.com/master/#XXXXX
<img src="http://example.com/image.jpg">
</a>
</textarea>
</p>
<p>
An ezine text link:<br>
<input type="text" name="b" size="46" value="http://example.com/master/#XXXXX">
</p>
</form>
But right now, when I use it, I have to refresh everytime I want to put a new value. I wanted to find a way on how I can generate more than once without having to refresh the page.
I tried editing some part of it but it's still only usable once. Is there a way to change that?
It's because findstring is always 'XXXXX' (it looks for value, which changes after click).
Replace old code with:
var findstring = "XXXXX";
function CreateAffiliateLink(F) {
var replacewith = F.AffCode.value;
if (replacewith.length < 1) return;
var re = new RegExp(findstring, "g")
for (i = 0; i < F.length; i++) {
var s = F.elements[i].value.toString();
if (s.length > 0) {
var newstr = s.replace(re, replacewith);
F.elements[i].value = newstr;
findstring = replacewith;
}
}
}
The reason it only works once is because it's looking for XXXXX in the URL, and replacing that with the affiliate code. But after you do a replacement, the URL no longer has XXXXX.
Use a more general regular expression that will match the master/# in the URL, and replace everything after it.
function CreateAffiliateLink(F) {
var replacewith=F.AffCode.value;
if (replacewith.length < 1) {
return;
}
replacewith = 'master/#' + replacewith;
var re = /master\/#\w+/g;
for (i = 0; i < F.length; i++) {
var s = new String(F.elements[i].value);
if (s.length > 0) {
var newstr = s.replace(re, replacewith);
F.elements[i].value = newstr;
}
}
}
<form name="me">
<p>
Type your affiliate code in the box and click the button:
<input type="text" name="AffCode" size="17">
<input type="button" value="Personalize links with my affiliate code" onClick="CreateAffiliateLink(this.form)">
</p>
<p>
Image link:<br>
<textarea name="a" cols="46" rows="3" wrap="off">
<a href="http://example.com/master/#XXXXX">
<img src="http://example.com/image.jpg">
</a>
</textarea>
</p>
<p>
An ezine text link:<br>
<input type="text" name="b" size="46" value="http://example.com/master/#XXXXX">
</p>
</form>

Get the element name attribute in JavaScript

How can I get the element name attribute in JavaScript?
HTML :
<input class="so" name="Name" value="bob"></input>
<input class="so" name="LastName" value="Feyzi"></input>
<input class="so" name="Email"></input>
<input class="so" name="Address"></input>
<input type="submit"></input>
JavaScript :
var person={};
var cars = document.querySelectorAll(".so");
for (i = 0; i < cars.length; i++) {
var elname = document.getElementByClassName('.so')[i].getAttribute('name');
//var eln = document.getElementsByTagName("input")[i].getAttribute("name");
var vala = document.querySelectorAll('.so')[i].value;
//alert(vala);
alert(elname);
}
After I run the script I want the person object to be set with this data:
person {
Name: "bob",
LastName: "Feyzi",
Email: "",
Adderss: ""
}
JSFiddle
Use the collection that you've already found with querySelectorAll to get the values of the value and name attributes :
var person = {}
var cars = document.querySelectorAll(".so")
for (i = 0; i < cars.length; i++) {
person[cars[i].name] = cars[i].value
}
console.log(person)
JSFiddle
Because getElementByClassName does not exist (also it would have no use in your script). Use this:
var person={};
var cars = document.querySelectorAll(".so");
for (i = 0; i < cars.length; i++) {
alert(cars[i].name)
}
Firstly, use cars variable instead of calling querySelectorAll every time.
Secondly, use addEventListener to execute code on click.
Fiddle: http://jsfiddle.net/guyavunf/3/
Code:
// HTML
<input class="so" name="Name" value="bob"></input>
<input class="so" name="LastName" value="Feyzi"></input>
<input class="so" name="Email"></input>
<input class="so" name="Address"></input>
<input class="submit" type="submit"></input>
// JS
document.querySelector('.submit').addEventListener('click', function() {
var person={};
var cars = document.querySelectorAll(".so");
for (i = 0; i < cars.length; i++) {
var name = cars[i].name;
var value = cars[i].value;
alert(name + ': ' + value);
}
});

How to apply a class attribute to an HTML string (not rendered on the document)

I am am developing code for am automator to improve the project with several pages.
I have a textarea input where I can enter HTML and it shows me the HTML with the right structure.
HTML:
<textarea name="message">
<input type="text" value="TextTwo" id="texttwo"/>
<input type="text" value="DataOne" id="dataone"/>
<input type="text" value="NumberTwo" id="numbertwo"/>
<input type="text" value="TextOne" id="textone"/>
<input type="text" value="DataTwo" id="datatwo"/>
<input type="text" value="NumberOne" id="numberone"/>
</textarea>
<button>process</button>
JS/JQuery:
$('button').click(function () {
var code = $('textarea[name=message]').val();
if ($('#output').length < 1) {
$("body").append('<h2>Output</h2><textarea id="output" rows="10" cols="100"></textarea>');
}
$('#output').val(code);
});
I would like to apply classes following these rules:
The input that has the word "Text" value in applying the class = "text"
The input that has the word "Data" value in applying the class = "data"
The input that has the word "Number" value in applying the class = "number"
An example of how the code would output in textarea
<input type="text" value="TextTwo" id="texttwo" class="text" />
<input type="text" value="DataOne" id="dataone" class="data" />
<input type="text" value="NumberTwo" id="numbertwo" class="number" />
<input type="text" value="TextOne" id="textone" class="text"/>
<input type="text" value="DataTwo" id="datatwo" class="data" />
<input type="text" value="NumberOne" id="numberone" class="number" />
DEMO CODE
What is a good approach to do this using JQuery?
I updated your fiddle and had this code working -- Can't give you a link since I don't actually have a fiddle account:
$('button').click(function () {
var code = $('textarea[name=message]').val();
// The best thing to do here is to turn that string of HTML into
// DOM elements and let the browser do the work.
var elms = jQuery.parseHTML(code);
var result = "";
// Now that we've processed the HTML into an array, work with it.
for (var i = 0; i < elms.length; i++) {
var el = elms[i];
if (el.tagName && el.tagName.toLowerCase() === "input") {
// Great! We we have an 'input' element.
var val = el.value;
if (val.indexOf("Text") !== -1) {
el.className = "text";
}
if (val.indexOf("Data") !== -1) {
el.className = "data";
}
if (val.indexOf("Number") !== -1) {
el.className = "number";
}
}
if (el.nodeType === 3) {
// Handle text nodes
result += el.nodeValue;
} else {
result += el.outerHTML;
}
}
if ($('#output').length < 1) {
$("body").append('<h2>Output</h2><textarea id="output" rows="10" cols="100"></textarea>');
}
$('#output').val(result);
});
Under the assumption that all the html in the textarea is valid, What we can do is just build the html into a div and then format the html with jQuery. After this is done just get the content and put it in the textarea.
$('button').click(function () {
var code = $('textarea[name=message]').val(),
$code = $('<div />').html(code),
classes = {'Text': 'text', 'Data': 'data', 'Number': 'number'};
if ($('#output').length < 1) {
$("body").append('<h2>Output</h2><textarea id="output" rows="10" cols="100"></textarea>');
}
$('input', $code).each(function(){
var t = this,
$t = $(this);
for(key in classes){
if(t.value.indexOf(key) > -1){
$t.addClass(classes[key]);
return;
}
}
});
$('#output').val($code.html());
});
http://jsfiddle.net/LC5y3/4/
DEMO
$('button').click(function () {
var code = $.parseHTML($('textarea[name=message]').val());
console.log(code);
var newCode = "";
code = $.grep(code, function (n, i) {
if (n.nodeValue) {
return n.nodeValue.trim()
} else {
return (n.outerHTML && n.outerHTML.trim())
}
});
for (var i = 0; i < code.length; i++) {
var element=$(code[i]);
element.addClass(element.attr("type"));
newCode += code[i].outerHTML;
}
console.log(newCode);
console.log(code);
if (!$('#output').length) {
$("body").append('<h2>Output</h2><textarea id="output" rows="10" cols="100"></textarea>');
}
$('#output').val(newCode);
});
You can use the attribute contains selector.
jsFiddle
$('input[id*="text"]').addClass('text');
$('input[id*="number"]').addClass('number');
$('input[id*="data"]').addClass('data');
You can dynamically build the elements:
$('input').addClass('className').attr('value','number');

Using for loop to generate text boxes

I want to be able to enter a number into a text box and then on a button click generate that number of text boxes in another div tag and automatically assign the id
Something like this but not sure how to generate the text boxes and assign automatically assign the id
function textBox(selections) {
for (i=0; i < selections +1; i++) {
document.getElementById('divSelections').innerHTML = ("<form><input type="text" id="1" name=""><br></form>");
}
}
Try this one:
function textBox(selections){
selections = selections*1; // Convert to int
if( selections !== selections ) throw 'Invalid argument'; // Check NaN
var container = document.getElementById('divSelections'); //Cache container.
for(var i = 0; i <= selections; i++){
var tb = document.createElement('input');
tb.type = 'text';
tb.id = 'textBox_' + i; // Set id based on "i" value
container.appendChild(tb);
}
}
A simple approach, which allows for a number to be passed or for an input element to be used:
function appendInputs(num){
var target = document.getElementById('divSelections'),
form = document.createElement('form'),
input = document.createElement('input'),
tmp;
num = typeof num == 'undefined' ? parseInt(document.getElementById('number').value, 10) : num;
for (var i = 0; i < num; i++){
tmp = input.cloneNode();
tmp.id = 'input_' + (i+1);
tmp.name = '';
tmp.type = 'text';
tmp.placeholder = tmp.id;
form.appendChild(tmp);
}
target.appendChild(form);
}
Called by:
document.getElementById('create').addEventListener('click', function(e){
e.preventDefault();
appendInputs(); // no number passed in
});
JS Fiddle demo.
Called by:
document.getElementById('create').addEventListener('click', function(e){
e.preventDefault();
appendInputs(12);
});
JS Fiddle demo.
The above JavaScript is based on the following HTML:
<label>How many inputs to create:
<input id="number" type="number" value="1" min="0" step="1" max="100" />
</label>
<button id="create">Create inputs</button>
<div id="divSelections"></div>
See below code sample :
<asp:TextBox runat="server" ID="textNumber"></asp:TextBox>
<input type="button" value="Generate" onclick="textBox();" />
<div id="divSelections">
</div>
<script type="text/javascript">
function textBox() {
var number = parseInt(document.getElementById('<%=textNumber.ClientID%>').value);
for (var i = 0; i < number; i++) {
var existingSelection = document.getElementById('divSelections').innerHTML;
document.getElementById('divSelections').innerHTML = existingSelection + '<input type="text" id="text' + i + '" name=""><br>';
}
}
</script>
Note: Above code will generate the N number of textboxes based on the number provided in textbox.
It's not recommended to user innerHTML in a loop :
Use instead :
function textBox(selections) {
var html = '';
for (i=0; i < selections +1; i++) {
html += '<form><input type="text" id="'+i+'" name=""><br></form>';
}
document.getElementById('divSelections').innerHTML = html;
}
And be carefull with single and double quotes when you use strings
You have to change some code snippets while generating texboxes, Learn use of + concatenate operator, Check code below
function textBox(selections) {
for (var i=1; i <= selections; i++) {
document.getElementById('divSelections').innerHTML += '<input type="text" id="MytxBox' + i + '" name=""><br/>';
}
}
textBox(4); //Call function
JS Fiddle
Some points to taken care of:
1) In for loop declare i with var i
2) your selection + 1 isn't good practice at all, you can always deal with <= and < according to loop's staring variable value
3) += is to append your new HTML to existing HTML.
ID should be generate manually.
var inputName = 'divSelections_' + 'text';
for (i=0; i < selections +1; i++) {
document.getElementById('divSelections').innerHTML = ("<input type='text' id= " + (inputName+i) + " name=><br>");
}
edit : code formated
Instead of using innerHTML, I would suggest you to have the below structure
HTML:
<input type="text" id="id1" />
<button id="but" onclick="addTextBox(this)">click</button>
<div id="divsection"></div>
JS:
function addTextBox(ops) {
var no = document.getElementById('id1').value;
for (var i = 0; i < Number(no); i++) {
var text = document.createElement('input'); //create input tag
text.type = "text"; //mention the type of input
text.id = "input" + i; //add id to that tag
document.getElementById('divsection').appendChild(text); //append it
}
}
JSFiddle

Categories

Resources