JavaScript:Choose Colour Randomly for a letter based upon input - javascript

I am writing a application which takes user inputs and assigns randomly the colors to each letter in the text.
HTML CODE
<label id="text">
Retrieve data from selected text input among various text inputs with same
name & id upon hitting Enter
</label>
<div>
<input type="text" id="inputColors">
</div>
<input id="Enter" type="button" value="Enter" />
JavaScript
document.getElementById("Enter").onclick = function() {
var colors = document.getElementById('inputColors').value;
var colorslist = colors.split(/[;,]+/);
$('#text').each(function() {
$(this).html($(this).text().split(' ').map(function(v) {
return '<span style="color:' + colorslist[Math.floor(Math.random() *
colorslist.length)] + '">' + v + '</span>';
}).join(' '));
});
}
I am able to color each word but would like it to do it for each letter.I dont want to use css.

Your code currently wraps a span around each word because it splits the string on the space character.
Instead you should split it using .split() which will return an array of all characters (including the spaces).
You then need to join them with nothing too using .join().
document.getElementById("Enter").onclick = function() {
var colors = document.getElementById('inputColors').value;
var colorslist = colors.split(/[;,]+/);
$('#text').each(function() {
$(this).html($(this).text().split('').map(function(v) {
return '<span style="color:' + colorslist[Math.floor(Math.random() *
colorslist.length)] + '">' + v + '</span>';
}).join(''));
});
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="text">
Retrieve data from selected text input among various text inputs with same name & id upon hitting Enter
</div>
<input type="text" id="inputColors" value="red,yellow,blue,green,orange" />
<input id="Enter" type="button" value="Enter" />

Related

how to get two word from a input field and make url based on another field

here i have two input field as like
$(document).ready(function() {
$("#business_name").keyup(function() {
var Text = $(this).val();
Text = Text.toLowerCase();
Text = Text.replace(/[^a-zA-Z0-9]+/g,'-');
$("#business_url").val(Text);
});
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<input type="text" id="business_name" name="business_name" placeholder="Business Name" />
<br><br>
<input type="text" id="business_url" name="business_url" placeholder="Business URL" />
now I want if someone wrote : My Business Name on first input field then 2nd field it will be write mybusiness thats it but now it showed my-business-name i dont want this (I need only two word if it will take longer name then it only shows first two word thats it )
To get only the first two words you can split() the string in to an array by spaces and then use slice() to get the first two elements of the resulting array. Then you can join it back together before displaying in the input.
Also note I added trim() and a regex to replace multiple whitespace with a single one, otherwise it would affect how split() builds the array and could end up missing words.
jQuery($ => {
$("#business_name").on('input', e => {
var text = $(e.target).val().trim().replace(/\s+/, ' ').toLowerCase().split(' ').slice(0, 2).join('');
$("#business_url").val(text);
});
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<input type="text" id="business_name" name="business_name" placeholder="Business Name" /><br /><br />
<input type="text" id="business_url" name="business_url" placeholder="Business URL" />
After replacing certain characters with ' ' count the number of ' ' in the string. If the count is 2 stop replacing or you can return from the function.
Look at the modified code below:
$(document).ready(function() {
var count = 0;
$("#business_name").keyup(function() {
var Text = $(this).val();
Text = Text.toLowerCase();
Text = Text.replace(/[^a-zA-Z0-9]+/g,' ');
count = (Text.split("-")).length - 1;
if (count == 2) {
return;
}
$("#business_url").val(Text);
});
});

Javascript Multiple Inputs Value Output

Hi I want to create a stamp script and I want the user to enter his name and address in three fields,
then he should see the fields later in the stamp edition?
I have 3 input fields where the user can give in his data,
now i will give this data in a new class. This is what i have:
window.onload = function() {
$( "#Text1" )
.keyup(function() {
var value = $( this ).val();
$( ".ausgabe" ).text( value );
})
.keyup();
};
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<input type="text" id="Text1">
<input type="text" id="Text2">
<input type="text" id="Text3">
<div class="ausgabe"></div>
It looks like you want to mimic what the user is typing in the text inputs and show it in ausgabe. If that's what you want, then you can tie the keyUp event to each of the inputs.
$(input [type='text']).keyUp(function() {
var value = $(this).val();
$('.ausgabe').text(value);
}
But this will overwrite .ausgabe every time text is entered into a different input.
You could get the value of .ausgabe every time keyUp fires and pre-pend that value:
So you may want to have a button that renders each input's value into .ausgabe:
<button>.click(function() {
$(input[type="text"]).each(function() {
var boxText = $(this).val(); //text box value
var aus = $('.ausgabe').text(); //ausgabe value
$('.ausgabe').text(boxText + ' ' + aus); //combine the current text box value with ausgabe
})
})
As you have not made it very clear what you are trying to accomplish, I am providing a simple example that might send you down the right path.
$(function() {
function updateDiv(source, target) {
var newVal = "";
source.each(function() {
newVal += "<span class='text " + $(this).attr('id').replace("Text", "item-") + "'>" + $(this).val() + "</span> ";
});
target.html(newVal);
}
$("[id^='Text']").keyup(function(e) {
updateDiv($("input[id^='Text']"), $(".ausgabe"));
});
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<input type="text" id="Text1">
<input type="text" id="Text2">
<input type="text" id="Text3">
<div class="ausgabe"></div>
Since you already seem to understand .html() and .text(), we can look at the Selector. The one used will select all elements with an ID Attribute of Text in the beginning of the string. See More: https://api.jquery.com/category/selectors/attribute-selectors/

Jquery Incrementing field names

Following on from my previous question
I've now got a form that when clicking add, adds a new input field to the form incrementing the field name and input text by one each time. eg: phone_number1, phone_number2 etc
The jquery I'm using is :
$(document).ready(function(){
var phone_number_form_index=1;
$("#add_phone_number").click(function(){
phone_number_form_index++;
$(this).parent().before($("#phone_number_form").clone().attr("id","phone_number_form" + phone_number_form_index));
$("#phone_number_form" + phone_number_form_index).css("display","inline");
$("#phone_number_form" + phone_number_form_index + " :input").each(function(){
$(this).parent().find('span').text('Phone number ' + phone_number_form_index);
$(this).attr("name",$(this).attr("name") + phone_number_form_index);
$(this).attr("id",$(this).attr("id") + phone_number_form_index);
});
$("#remove_phone_number" + phone_number_form_index).click(function(){
$(this).closest("div").remove();
});
});
});
This JFiddle shows the form working and when adding a new row the field name is incremented as is the input text.
http://jsfiddle.net/yezw6c51/25/
However if I remove a field, the numbering can get messed up.
eg:
With one field the input text and field names are Phone Number 1 /
phone_number1
With two fields the input text and field names are Phone Number 1 &
Phone Number 2 etc
With three fields the input text and field names are Phone Number 1 &
Phone Number 2 & Phone Number 3 etc
if I then remove phone number 2 using the remove button I end up with 1 & 3, clicking add starts at 4.
Is there any way if I delete 2 instead of 1 & 3, I would get 1, 2 and the next add would be 3 ?
This would need to update all field names and input text entries that are being updated.
After adding/removing you can renumber all the inputs and labels like follows:
$(document).ready(function(){
$("#add_phone_number").click(function(){
$(this).parent().before($("#phone_number_form").clone().show());
reNumberInputs();
});
$("form").on("click", "[id^='remove_phone_number']", function(){
$(this).closest("div").remove();
reNumberInputs();
});
});
function reNumberInputs() {
$("input[type='text']:visible").each(function(index, element) {
var displayIndex = (index + 1).toString();
element.id = "phone_number" + displayIndex;
element.name = "phone_number" + displayIndex;
if (index > 0) {
$(this).prev("span").html("Phone number " + displayIndex);
$(this).next("input").prop("id", "remove_phone_number" + displayIndex).prop("name", "remove_phone_number" + displayIndex);
}
});
}
.hidden {
display: none;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<div id="phone_number_form" class="hidden">
<p>
<span>Phone number</span> : <input type="text" name="phone_number" />
<input type="button" id="remove_phone_number" value="Remove" />
</p>
</div>
<form>
<p>
Phone number : <input type="text" name="phone_number1" />
</p>
<p>
<input type="button" value="Add phone number" id="add_phone_number" />
</p>
</form>
Updated Fiddle
You can use the field name as phone_number[] this will be the standard.
If you can't change the procedure then on submit of form rename your fields by getting all the created one by one and assigning current text field values to new fields but it is not a standard method.
Hope you get your answer and if you have any other question get in touch with me on my new blog on http://www.sourabhmodi.in/. I will be happy to help you..

Changing value of text field with jQuery

I have a form input text field, and I want to change the text inside of the text field when the user clicks a button. I can get the specific textfield with jQuery, but cannot change the text with .val(). Is there another way this can be done, or am I doing something wrong.
Here is the text field:
<input type="text" name="textBox" id="Stage 1text" size="20" value="Enter Current Comp." align="center">
Then I use this to identify and change the text field. where in this case stage = "Stage 1" and dance is the string I want to place in the text field.
str = "#" + stage + 'text';
alert(str + '::' + dance); // confirm that strings are correct
jQuery(str).val(dance);
An ID should not have spaces. Stage 1text is an invalid ID
Add an underscore instead of space
<input type="text" name="textBox" id="Stage_1text" size="20" value="Enter Current Comp." align="center">
and try below,
// v--- assuming this will be Stage_1
str = "#" + stage + 'text';
alert(str + '::' + dance); // confirm that strings are correct
jQuery(str).val(dance);
incase if stage is returned from backend.. then simply replace space with _
str = "#" + stage.replace(/ /g,"_") + 'text';
id attributes should not contain spaces.
You could change your code like so:
<input type="text" name="textBox" id="Stage_1text" size="20" value="Enter Current Comp." align="center">
str = "#" + stage.replace(' ','_') + 'text';
alert(str + '::' + dance); // confirm that strings are correct
jQuery(str).val(dance);

simpler way of grouping numerous variables by value of select?

thanks for looking.
im still learning the more complex javascript and jquery coding so could do with some help as i have no idea about the following or even if its possible!
i need a better/simpler/shorter way of doing the following (please note i have removed the irrelevant validation etc coding):
'
function Findbox5( myform, box1, box2, box3, box4, box5, Storeall, s1, s2, s3, s4, s5)
{
//store values
Myform = document.forms.myform;
box1 = Myform.box1.value;
box2 = Myform.box2.value;
box3 = Myform.box3.value;
box4 = Myform.box4.value;
box5 = Myform.box5.value;
s1 = Myform.s1.value;
s2 = Myform.s2.value;
s3 = Myform.s3.value;
s4 = Myform.s4.value;
s5 = Myform.s5.value;
//set as one string
Storeall = s1 + ":" + box1 + ";" + s2 + ":" + box2 + ";" + s3 + ":" + box3 + ";" + s4 + ":" + box4 + ";" + s4 + ":" + box5 + ";" ;
// next function...
} '
as you can see i have 5 input boxes and relevant selects for each box(each select has 4 options:1,2,3,4.). when a user enters data into a box they choose a relevant option. all boxes and options must be entered then they submit the form.
this data will be emailed to me as the variable stored under storeall. which would be something like 1:1234;2:1324;1:3232;4:5434;2:3211;
so what i hope to do is simplify this data into the following with either a seperate function or the same one: 1:1234-3232;2:1324-3211;4:5434;
is this possible? or have i done it the easiest way?
any comments or help welcomed, thanks again
First, you'll want to group these things into a single element that can be iterated against. So if your HTML looks like:
<form>
<input name="s1" />
<input name="box1" />
<input name="s2" />
<input name="box2" />
...
</form>
Then it's probably better to do something like:
<form>
<div class="set">
<input class="s" name="s1" />
<input class="box" name="box1" />
</div>
<div class="set">
<input class="s" name="s2" />
<input class="box" name="box2" />
</div>
...
</form>
Now you've established some commonality among these elements, instead of just different names/IDs. Each set of inputs is grouped by the .set class, and within each set, you know there's going to be two inputs: one with the .s class, and one with the .box class. Now iterating against them with JQuery is easy:
var str = "";
$("form div.set").each(
function(index, element)
{
currentValueS = $(element).find("input.s").val();
currentValueBox = $(element).find("input.box").val();
str += currentValueS + ":" + currentValueBox + ";";
}
);
This uses JQuery's .each() function. .each() allows you to provide a function to perform on each of the elements that JQuery finds from the indicated selector. Here, your selector is form div.set, which means "all div elements that have the class of .set, and are found anywhere under any form element". For each of these elements, you'll need to find the value of the <input> element with the .s class, and also the value of the <input> element with the .box class. Then you just add those to your growing str variable.
If you want everything in the form, you should use serializeArray :
$('#my_form').submit(function() {
var str = '';
$.each($(this).serializeArray(), function () {
str += this.name + ":" + this.value + ";";
});
sendByMail(str);
return false;
});

Categories