Javascript input field should append in div whille Typing - javascript

I am building an Url-Generator for google analytics. Currently, the Url is appending if I press the submit button. But I want the URL to append while typing in the input. How can I do that with Javascript to get rid of the submit button?
PS: I also want that if I make changes for example in the third input field that the sequence isn't changing (that the content of the third input field isn't appending at last, after I have changed the input value).
HERE'S MY CURRENT CODE THAT LET'S THE URL APPEND AFTER PRESSING THE SUBMIT BUTTON:
//create URL
submit.addEventListener("click", function() {
outputField.value = "";
output = "";
//lowercases all field inputs
if(input01.value !== "" && input02.value !== "") {
output += input01.value + "?utm_source=" + input02.value;
if(createClicked === false) {
$("#outputWrapper").slideToggle(550);
createClicked = true;
}
} else {
alert("Website Url and Campaign Source can't be empty");
}
if(input03.value !== "") {
output += "&utm_medium=" + input03.value;
}
if(input04.value !== "") {
output += "&utm_campaign=" + input04.value;
}
if(input05.value !== "") {
output += "&utm_term=" + input05.value;
}
if(input06.value !== "") {
output += "&utm_content=" + input06.value;
}
//output.toLowerCase();
//removes space through %20 in output
output = output.replace(/\s/g,'%20');
outputField.textContent = output;
})

attach an eventListener to your input and listen for the input event
let myText = document.querySelector('#myText');
document.querySelector('#myInput').addEventListener('input', function(){
myText.innerText = this.value;
});
span{
display : block;
}
<input type="text" id="myInput" />
<span id="myText"></span>

Related

Yii 2 kartik dialog.prompt with input type textarea

I have a button that triggers a kartik dialog.prompt, where text is put in.
I need the input in the dialog to have several rows and line breaking capability (like textarea)
How to change it from a simple text input to textarea?
Here is my javascript:
$("#bulk-email-button-invitations").on("click", function() {
var grid = $("#invitations");
var keys = grid.yiiGridView('getSelectedRows');
if (keys.length >= 1){
krajeeDialog.prompt({label:'Text emailu:', placeholder:'Zadejte text emailu'}, function (result) {
if (result) {
$(location).attr('href', '/educational-event-invitation/bulk-email?' + $.param({invitations: keys, text: result}));
} else {
krajeeDialog.alert('Text emailu nesmí být prázdný!');
}
});
}else{
krajeeDialog.alert("Nejprve vyberte studenty, kterým chcete poslat email!")
}
});
I found that if type is not defined (unlike label and placeholder in my case), it defaults to "text". But I wasn't able to make the dialog render any type other than a simple one-row text input.
Apparently, this is not supported in the extension.
Reason:
The reason is that in the dialog.js where the KrajeeDialog.prototype is defined the function bdPrompt is the one that takes care of the prompt dialog that is to be created and it creates the default field type as input rather than deciding on any of the options or parameters passed to KrajeeDialog.prompt() although you can pass a parameter of name type like
krajeeDialog.prompt({
label:'Text emailu:',
placeholder:'Zadejte text emailu',
type:'password'
},function(){})
but this does not decide if the element will be input or textarea type, this parameter type is passed as the attribute of the input element. See the below code block to understand the reason i explained the third line will always create a field of type input.
File yii2-dialog/assets/js/dialog.js Line 110
if (typeof input === "object") {
$inputDiv = $(document.createElement('div'));
$input = $(document.createElement('input'));
if (input['name'] === undefined) {
$input.attr('name', 'krajee-dialog-prompt');
}
if (input['type'] === undefined) {
$input.attr('type', 'text');
}
if (input['class'] === undefined) {
$input.addClass('form-control');
}
$.each(input, function(key, val) {
if (key !== 'label') {
$input.attr(key, val);
}
});
if (input.label !== undefined) {
msg = '<label for="' + $input.attr('name') + '" class="control-label">' + input.label + '</label>';
}
$inputDiv.append($input);
msg += $inputDiv.html();
$input.remove();
$inputDiv.remove();
} else {
msg = input;
}
So you might need to override the javascript function according to your needs if you want to work it that way.
It is possible to add custom html to krajeeDialog.prompt after all.
In the documentation, kartik-v states:
content: string|object: If set as a string, it is treated as a raw HTML content that will be directly displayed.
So if I replace the original object in my code with a string containing the desired html, it will render my textarea or any other form element.
For example, replace it with a textarea html:
$("#bulk-email-button-invitations").on("click", function() {
var grid = $("#invitations");
var keys = grid.yiiGridView('getSelectedRows');
if (keys.length >= 1){
krajeeDialog.prompt('<textarea>Sample text...</textarea>', function (result) {
if (result) {
$(location).attr('href', '/educational-event-invitation/bulk-email?' + $.param({invitations: keys, text: result}));
} else {
krajeeDialog.alert('Text emailu nesmí být prázdný!');
}
});
}else{
krajeeDialog.alert("Nejprve vyberte studenty, kterým chcete poslat email!")
}
});

How to setup a list with removable items that stores itself in localStorage in javaScript

I have been working on a little project and I need some values to be stored in an array, that would be displayed at all times, even if the page reloads, and that could be removed by pressing a button.
The idea that I had is to store the array in localStorage, and every time the page loads, they get downloaded into the javascript array.
That seems to work flawlessly, but my problems come when I am trying to remove them by pressing a button. I know where the problem in my code is, I just don't know how to do it so that it works.
The problem is that, after I delete an item with a low index, it messes with my ability to later delete items with higher index.
Here's the code:
var input = document.getElementById("text");
var displayed = input.value;
var a = [];
function check() {
if (localStorage.session == null) {
a.push(JSON.parse(localStorage.getItem('session')));
a.splice(0, 1);
localStorage.setItem('session', JSON.stringify(a));
}
}
function SaveDataToLocalStorage() {
a = JSON.parse(localStorage.getItem('session'));
if (input.value !== "input") {
a.push("<p>" + input.value + " </p><button onclick='Delete(" + (a.length - 1) + ")'>Delete</button><br />");
} else {
displayed = "";
}
localStorage.setItem('session', JSON.stringify(a));
document.getElementById("Demo").innerHTML = a.join("");
}
function Delete(deleted) {
var index = deleted;
a.splice(deleted, 1);
localStorage.setItem('session', JSON.stringify(a));
document.getElementById("Demo").innerHTML = a.join("");
}
check();
SaveDataToLocalStorage();
<input type="text" name="input" value="input" id="text">
<button onclick="SaveDataToLocalStorage()">Click</button>
<div id="Demo">
If anyone could help, It would be Amazing!
I didn't test the code but I think this can help you out!
var input = document.getElementById("text");
var displayed = input.value;
var a = [];
function check() {
if (localStorage.session == null) {
a.push(JSON.parse(localStorage.getItem('session')));
a.splice(0, 1);
localStorage.setItem('session', JSON.stringify(a));
}
}
function SaveDataToLocalStorage() {
a = JSON.parse(localStorage.getItem('session'));
if (input.value !== "input") {
a.push({
index: a.length,
data: "<p>" + input.value + " </p><button onclick='Delete(" + a.length + ")'>Delete</button><br />"
});
} else {
displayed = "";
}
localStorage.setItem('session', JSON.stringify(a));
document.getElementById("Demo").innerHTML = a.join("");
}
function Delete (deleted) {
a = a.filter(function (e) { return e.index !== deleted })
localStorage.setItem('session', JSON.stringify(a));
document.getElementById("Demo").innerHTML = a.join("");
}
check();
SaveDataToLocalStorage();
<input type="text" name="input" value="input" id="text">
<button onclick="SaveDataToLocalStorage()">Click</button>
<div id="Demo">
Your problem is with this
a.push("<p>" + input.value + " </p><button onclick='Delete(" + (a.length - 1) + ")'>Delete</button><br />");
You're hardcoding the index to delete in the Delete button, but the index can change if you delete an item from earlier in the array.
You could consider re-rendering everything, including the buttons, every time your array changes.
Another alternative is that every item in your array can have an ID, and that would not change when an earlier one is deleted. Then you can make your 'delete' function remove an element from the array based on its ID.
One more solution: make the button click function check it's own index upon click (eg check if it's the 2nd delete button or the 9th delete button), and delete from the array the index that it gets from that check. That way you can keep most of your code the same, but the index isn't hardcoded into the button, it's live-checked every time.

looping in javascript using array

i have html code for input file, it have id and name
<input type="file" id="file1" name="my_field[]" class="image-upload" />
for validate input form, i check value using id but i have many input.
var count=0;
if(document.getElementById("file1").value != "") {
// you have a file
count = count + 1;
}
if(document.getElementById("file2").value != "") {
// you have a file
count = count + 1;
}
i want using getElementByName with array. this is what i have try:
for(i=0;i<6;i++)
{
if(document.getElementByName("my_field["+i+"]").value != "") {
// you have a file
count = count + 1;
}
}
Still not working. any suggest?
You already have unique id values. Use those.
...
if(document.getElementById("file" + my_field[i].toString()).value != "") {
...

Check if placeholder text already exists within a string

I have an #error paragraph. Everytime there is an error within the form on submit. The inputs placeholder text gets added to the #error paragraph.
My problem:
It happens everytime a user clicks submit. So the #error message returns:
Please fill in yourfirst name, last name, company, position, first
name, last name, company, position, first name, last name, company,
position, first name, last name, company, position, first name, last
name, company, position, first name, last name, company, position,
I've looked for other solutions and tried this:
if (input.attr('placeholder').indexOf($('#error')) >= 0){
} else{
$('#error').append(input.attr('placeholder').toLowerCase() + ', ');
}
Is there any way to check if the placeholder text already exists in the #error message? Here's a fiddle. I'm sorry it's so convoluted. But its what i've been working on and had it handy.
Thanks for your help in advance!
http://jsfiddle.net/8YgNT/20/
var errorText = '';
//Validate required fields
for (i = 0; i < required.length; i++) {
var input = $('#' + required[i]);
if ((input.val() == "") || (input.val() == emptyerror)) {
input.addClass("tobefixed");
errornotice.fadeIn(750);
if (input.attr('placeholder').indexOf($('#error')) >= 0) {
// do nothing
} else {
errorText = errorText + $(input).attr('placeholder').toLowerCase() + ', ';
}
input.val(emptyerror);
errornotice.fadeIn(750);
} else {
input.removeClass("tobefixed");
}
}
$('#error').html('').append('Please fill in your ' + errorText);
I simple add one line in your fiddle and it's working now:
required = ["id_first_name", "id_last_name", "id_firmbox", "id_job_title"];
errornotice = $("#error");
emptyerror = "Please fill out this field.";
$("#startform").submit(function(){
//Validate required fields
$("#error").html("Please fill in your");
for (i=0;i<required.length;i++) {
var input = $('#'+required[i]);
if ((input.val() == "") || (input.val() == emptyerror)) {
input.addClass("tobefixed");
errornotice.fadeIn(750);
// =====Here===== //
if (input.attr('placeholder').indexOf($('#error')) >= 0){
} else{
$('#error').append(input.attr('placeholder').toLowerCase() + ', ');
}
// ============== //
input.val(emptyerror);
errornotice.fadeIn(750);
} else {
input.removeClass("tobefixed");
}
}
if ($(":input").hasClass("tobefixed")) {
return false;
} else {
errornotice.hide();
return true;
}
});
$(":input").focus(function(){
if ($(this).hasClass("tobefixed") ) {
$(this).val("");
$(this).removeClass("tobefixed");
}
});
This line do the all trick:
$("#error").html("Please fill in your");
Saludos ;)
If you want to check whether #error contains the string you're wondering about, you can use
($('#error').text().indexOf(a_string)) != -1
This will return true if #error contains a_string.
There's a longer discussion on searching strings for other strings in this question.
It seems you're doing it the wrong way round (and forgetting to get the text out of the #error element):
if ( $('#error').text().indexOf( input.attr('placeholder') ) >= 0)

How do I add dynamic content to a div generated dynamically?

Basically I am validating a form, I am collecting the error messages and I am appending them to a div generated dynamiclly. Now I am unable to append these message to this div .here is what I had done
//generates a div onclick of submit button
$("body").append("<div class='overlay'><div class='errorContainer'>.html(errorMsg)</div><div>`<a href='javascript:void(0);' class='cross'>X</a><div></div>");
.html(errorMsg) this causes error/is incorrect
function closeErrorBox() {
var errorMsg = "";
var ferrorMsg = "Please say your first name" + "<br>";
var aerrorMsg = "Please type address" + "<br>";
var eerrorMsg = "Please type a valid email Address" + "<br>"
if($("#name").val() == "") {
errorMsg += ferrorMsg;
}
if($("#address").val() == "") {
errorMsg += aerrorMsg;
}
if($("#email").val() == "") {
errorMsg += eerrorMsg;
}
$(".errorContainer").html(errorMsg);
$(".overlay").remove();
}
The .errorContainer div is inside the .overlay div. When you remove overlay in the end of your function, errorContainer is removed too. Other than that, it seems the .html(errorMsg)
is working fine (if it still causing error, please specify what's going wrong).
Re-reading your question, I couldn't understand you program's flow: are you adding that div when the error is already known, and closing it when you click the "X"? If thats the case, I'd suggest doing something like this:
var errorMsg = "";
var ferrorMsg = "Please say your first name" + "<br>";
var aerrorMsg = "Please type address" + "<br>";
var eerrorMsg = "Please type a valid email Address" + "<br>"
if($("#name").val() == "") {
errorMsg += ferrorMsg;
}
if($("#address").val() == "") {
errorMsg += aerrorMsg;
}
if($("#email").val() == "") {
errorMsg += eerrorMsg;
}
// Adapting Diego's answer:
$("<div class='overlay'><div class='errorContainer'></div><div><a href='javascript:void(0);' class='cross'>X</a><div></div>")
.appendTo($("body"))
.find(".errorContainer")
.html(errorMsg)
.end()
.find(".cross")
.click(function(e) {
e.preventDefault();
$(this).closest(".overlay").remove();
});
I think you meant:
//generates a div onclick of submit button
$("body").append("<div class='overlay'><div class='errorContainer'></div><div><a href='javascript:void(0);' class='cross'>X</a><div></div>").find(".errorContainer").html(errorMsg);

Categories