Make a button submittable more than once - javascript

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>

Related

textarea isn't reading input that I have made [duplicate]

This question already has answers here:
Why does jQuery or a DOM method such as getElementById not find the element?
(6 answers)
Closed 1 year ago.
So no matter what I change if I input anything in the textarea it is not reading anything from the form.
I needed it to be able to have input and not just change the default message of the textarea. If there is any other error in my code please help me by correcting me. And this is only purely html and javascript.
function manage(txt) {
var input = document.getElementById('replace');
if (txt.value != '') {
input.disabled = false;
}
else {
input.disabled = true;
}
}
function findReplace() {
var str = document.getElementById("message").innerHTML;
var find = document.getElementById("find").value;
var replace = document.getElementById("replace").value;
var res = str.replaceAll(find, replace);
document.getElementById("message").innerHTML = res;
}
function Counter(str) {
var str = document.getElementById("message").innerHTML;
var msg = str.split(" ");
var element = document.getElementById("replace").value;
var count = 0;
for ( var i = 0; i < msg.length; i++)
{
if (element == msg[i])
{
count++;
i++;
} else
{
i++;
}
document.getElementById("demo").innerHTML = "Number of replacement: " + count;
}
}
<!-- Message -->
<label for="message">Message: </label><br>
<textarea required type = "text" id="message" name = "message" rows="3" cols="20" method = "post">Hello testing</textarea><br>
<!-- Finding box -->
<label for="find">Find: </label><br>
<input type="text" id="find" name="find" onkeyup = "manage(this)"><br>
<!-- Replace box -->
<label for="replace">Replace with: </label><br>
<input disabled type="text" id="replace" name="replace">
<!--Submit button -->
<input type="button" value="find and replace" onclick ="findReplace(); Counter();">
Try value instead of innerHTML for textarea control.
function findReplace() {
var str = document.getElementById("message").value; //use value here
console.log(str)
var find = document.getElementById("find").value;
var replace = document.getElementById("replace").value;
var res = str.replaceAll(find, replace);
document.getElementById("message").value = res; //use value here
}
Note: There is no element with id demo in the HTML which is used in your JS.
Demo:
function manage(txt) {
var input = document.getElementById('replace');
if (txt.value != '') {
input.disabled = false;
}
else {
input.disabled = true;
}
}
function findReplace() {
var str = document.getElementById("message").value;
console.log(str)
var find = document.getElementById("find").value;
var replace = document.getElementById("replace").value;
var res = str.replaceAll(find, replace);
document.getElementById("message").value = res;
}
function Counter(str) {
var str = document.getElementById("message").innerHTML;
var msg = str.split(" ");
var element = document.getElementById("replace").value;
var count = 0;
for ( var i = 0; i < msg.length; i++)
{
if (element == msg[i])
{
count++;
i++;
} else
{
i++;
}
//document.getElementById("demo").innerHTML = "Number of replacement: " + count;
}
}
<!-- Message -->
<label for="message">Message: </label><br>
<textarea required type = "text" id="message" name = "message" rows="3" cols="20" method = "post">Hello testing</textarea><br>
<!-- Finding box -->
<label for="find">Find: </label><br>
<input type="text" id="find" name="find" onkeyup = "manage(this)"><br>
<!-- Replace box -->
<label for="replace">Replace with: </label><br>
<input disabled type="text" id="replace" name="replace">
<!--Submit button -->
<input type="button" value="find and replace" onclick ="findReplace(); Counter();">

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

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('>', ''))

Display the results in a text box

I have this code where a user types a phrase or word and it reverses the string, but my problem is that I would like for it to display the results in the very same text box the user typed the word. Here’s my code:
function revme() {
var textb = document.getElementById("textb");
var str = textb.value;
var str1 = "";
l = str.length;
for (i = l; i >= 0; --i) {
str1 = str1 + str.substring(i, i + 1);
}
document.getElementById("results").innerHTML = str1;
}
Please enter your text
<br>
<input type="text" id="textb">
<p id="results"></p>
<input type="button" value="Reverse" onclick="revme()">
I tried to do it like this:
document.getElementById("textb").innerHTML = str1;
But that doesn’t work. Any Ideas?
The problem with your code is that you're setting the innerHTML of textbox. Instead, you should set the value of the textbox.
Demo
var textb = document.getElementById("textb");
function revme() {
var str = textb.value;
var str1 = "";
l = str.length;
for (i = l; i >= 0; --i) {
str1 = str1 + str.substring(i, i + 1);
}
textb.value = str1;
// ^^^^^^^^^^^^^^^^
}
Please enter your text
<br>
<input type="text" id="textb">
<p id="results"></p>
<input type="button" value="Reverse" onclick="revme()">
Another way to reverse string will be using string and array functions as follow. I'll also recommend you to use addEventListener instead of inline event handlers.
Demo
var textb = document.getElementById("textb");
document.getElementById('reverse').addEventListener('click', function() {
var str = textb.value || '';
textb.value = str.split('').reverse().join('');
}, false);
Please enter your text
<br>
<input type="text" id="textb">
<p id="results"></p>
<input type="button" id="reverse" value="Reverse" />
Let it done done by this .. i am getting the exact reverse pattern of any value i enter.
<html>
<body>
Please enter your text<br>
<input type="text" id="textb">
<p id="results"></p>
<input type="button" value="Reverse" onclick="revme()">
</body>
<script>
function revme() {
var textb = document.getElementById("textb");
var str = textb.value;
var str1 = "";
l = str.length;
for (i = l ; i >=0 ; --i ){
str1 = str1 + str.substring(i,i+1);
}
document.getElementById("textb").value= str1;
}
</script>
</html>

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');

Count and display number of characters in a textbox using Javascript

I am working on a project that requires me to count the number of characters entered in a text box and dynamically display the result elsewhere on the page.
As I said, this would preferably be done in jQuery or Javascript.
Thanks in advance.
You could do this in jQuery (since you said you preferred it), assuming you want the character count displayed in a div with id="characters":
$('textarea').keyup(updateCount);
$('textarea').keydown(updateCount);
function updateCount() {
var cs = $(this).val().length;
$('#characters').text(cs);
}
UPDATE: jsFiddle (by Dreami)
UPDATE 2: Updating to include keydown for long presses.
This is my preference:
<textarea></textarea>
<span id="characters" style="color:#999;">400</span> <span style="color:#999;">left</span>
Then jquery block
$('textarea').keyup(updateCount);
$('textarea').keydown(updateCount);
function updateCount() {
var cs = [400- $(this).val().length];
$('#characters').text(cs);
}
<script type="text/javascript">
function countChars(countfrom,displayto) {
var len = document.getElementById(countfrom).value.length;
document.getElementById(displayto).innerHTML = len;
}
</script>
<textarea id="data" cols="40" rows="5"
onkeyup="countChars('data','charcount');" onkeydown="countChars('data','charcount');" onmouseout="countChars('data','charcount');"></textarea><br>
<span id="charcount">0</span> characters entered.
Plain Javascript.
I would like to share my answer which i used in my project and it is working fine.
<asp:TextBox ID="txtComments" runat="server" TextMode="MultiLine" Rows="4" Columns="50" placeholder="Maximum limit: 100 characters"></asp:TextBox><br />
<span id="spnCharLeft"></span>
<script type='text/javascript'>
$('#spnCharLeft').css('display', 'none');
var maxLimit = 100;
$(document).ready(function () {
$('#<%= txtComments.ClientID %>').keyup(function () {
var lengthCount = this.value.length;
if (lengthCount > maxLimit) {
this.value = this.value.substring(0, maxLimit);
var charactersLeft = maxLimit - lengthCount + 1;
}
else {
var charactersLeft = maxLimit - lengthCount;
}
$('#spnCharLeft').css('display', 'block');
$('#spnCharLeft').text(charactersLeft + ' Characters left');
});
});
</script>
Source: URL
Though it has been already solved, I'm interested to share something that I have used in one of my projects:
<textarea id="message" cols="300" rows="200" onkeyup="countChar(this)"
placeholder="Type your message ..." >
</textarea>
<input id="text-character" class="input-mini uneditable-input"
placeholder="0 Chars" readonly />
<input id="text-parts" class="input-mini uneditable-input"
placeholder="0 Parts" readonly />
<input id="text-remaining" class="input-medium uneditable-input"
placeholder="160 Chars Remaining" readonly />
Javascript code:
function countChar(val) {
var len = val.value.length;
var ctext = len + " Chars";
var str = val.value;
var parts = [];
var partSize = 160;
while (str) {
if (str.length < partSize) {
var rtext = (partSize - str.length) + " Chars Remaining";
parts.push(str);
break;
}
else {
parts.push(str.substr(0, partSize));
str = str.substr(partSize);
}
}
var ptext = parts.length + " Parts";
$('#text-character').val(ctext);
$('#text-parts').val(ptext);
$('#text-remaining').val(rtext);
}
<script Language="JavaScript">
<!--
function Length_TextField_Validator()
{
var len = form_name.text_name.value.length; //the length
return (true);
}
-->
</script>
<form name="form_name" method="get" action="http://www.codeave.com/html/get.asp"
onsubmit="return Length_TextField_Validator()">
<input type="text" name="text_name">
<input type="submit" value="Submit">
</form>
Source(s) : Text Validation

Categories

Resources