TextBox create div javascript - javascript

I want to create different "div" in the body when the user enter the number of div in the textbox
For example, with the markup for my textbox: <input type="text" id="numberDiv" maxlength="1">
I am using the following JS:
<script>
$(document).ready(
function () {
$('#numberDiv').keyup(
function () {
var s = $("#numberDiv").val();
var nbrDiv = parseInt(s);
for(var i = 0; i <= nbrDiv; i++)
{
var iDiv = document.createElement('div');
iDiv.id = 'div';
document.getElementsByTagName('body')[0].appendChild(iDiv);
iDiv.innerHTML = "I'm a div";
}
})
});
</script>
My problem is when I put for example "1" in the textbox it creates 1 div but when I press an other key (for example: enter, alt, ...) it creates another div even if my input has the maxlength="1". How can I disable the pressing on another key when my first number is in the textbox.

First of all, you shouldn't use the same id for all of the divs. So instead of iDiv.id = 'div' you might want to do this:
iDiv.attr('id', 'div[' + i + ']');
I'm not sure about your requirements, but you might also want to check the number of divs before creating new ones:
$('#numberDiv').keyup(function() {
var s = $(this).val();
var currentDivsCount = $('body > div').length;
var nbrDiv = parseInt(s, 10) - currentDivsCount;
if (isNaN(nbrDiv)) return;
var iDiv;
for (var i = 0; i < Math.abs(nbrDiv); i++) {
if (nbrDiv > 0) {
iDiv = $('<div>I\'m a div</div>');
iDiv.attr('id', 'div[' + (currentDivsCount + i) + ']');
iDiv.appendTo('body');
} else {
$('body > div:last').remove();
}
}
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input type="text" id="numberDiv" maxlength="1">

you can mask your input like so:
first Import the jQuery mask library,
Textbox : <input type="text" id="numberDiv" maxlength="1">
$(document).ready(
function () {
$('#numberDiv').mask('0');
});
this will only allow 1 number (digit character) to be in the box at a time
look here for more examples
and here to download the mask plugin

either you put the check on keycode for using event, if it is for numeric value then only run the logic. simple if in function will work.
<script>
$( "#whichkey" ).on( "keydown", function( event ) {
if( event.which < // range for 1 to 9){
//logic comes here
}
});
</script>
or you can add code to remove innerhtml before adding the div. So even if user press anyother key like enter. It will delete the innerhtml and then add the 1 div.

Related

Using a javascript button to change html, with multiple values that are picked using an auto incrementing number

Basic html:
<button id="changer">Changer button</button>
<div id="text"> </div>
"Changer" is the button element in html, "text" is the div tag in which our text will be placed.
var selector = 0;
We set the selector to 0. Next, every time the button "changer" is clicked, we add 1 to the selector var, unless it has reached its max value of 14, in which case we start over. And based on the selector value, we pick from the available text values.
document.getElementById("Changer").onclick = function () {
if (selector < 14) {
selector++;
}
else {
selector = 0;
selector++;
}
document.getElementById("text").innerHTML = text;
}
if (selector = 1 ){
text = "<p>this is text 1</p>";
if (selector = 2 ){
text = "<p>this is text 2</p>";
etc...
The problem is, the function upon being clicked jumps right to the last text value available. How do I fix this? Will add live example soon if needed.
Your are assigning the selector inside the if condition to a value.
if(selector = 1) {...
What you actually want to do is check if the selectors value is equal to something like so:
if(selector == 1) {...
But you do not need to repeat the check, you can simply do:
var selector = 0;
var btn = document.getElementById('changer');
var output = document.getElementById('text');
btn.addEventListener('click', function() {
if (selector < 14) {
selector++;
output.innerHTML = "<p>this is text " + selector + "</p>";
} else {
selector = 0;
output.innerHTML = "";
}
})
<button id="changer">Changer button</button>
<div id="text"> </div>

Multiple Functions with one Code

so I'm using this code, to slideToggle a box on my webpage.
// OPEN CERTAIN BOX
$(function() {
var sliding = false;
var mq = window.matchMedia( "(min-width: 700px)" );
if (mq.matches) {
var time = 500;
} else {
var time = 0;
}
var id = ('1');
var div = ('#toggle-content-' + id);
var img = ('#toggle-img-' + id);
var toggler = ('toggler-' + id);
$(div).hide()
$(toggler).click(function() {
if (sliding == false) {
sliding = true;
// Open / Close
$( div ).slideToggle(time,"swing");
// ...
As you can see, I'm using the var id, to use the toggle function for a certain box, which has its own css and html code.
I have 7 more boxes. Until now, i copied the code 7 times and changed the id at each copy from 2 - 8. Is there a way to make it with one code?
I tried a for loop, that goes from 1 - 8 but this obviously didnt work.
Has someone an idea? Or do I have to make that 8 copies and changed the id.
Edit:
My approach with the for-loop:
$(function() {
var sliding = false;
var mq = window.matchMedia( "(min-width: 700px)" );
if (mq.matches) {
var time = 500;
} else {
var time = 0;
}
for(i = 1; i <= 8; i++){
var id = (i.toString());
var div = ('#toggle-content-'+id);
var img = ('#toggle-img-'+id);
var toggler = ('toggler-'+id);
$( div ).hide()
$( toggler ).click(function(){
if (sliding == false){
sliding = true;
// Open / Close
$( div ).slideToggle(time,"swing");
...
And this is my html code for one box:
<tr><td cellspacing="0" cellpadding="0" height="50px" class="upper">
<toggler-1><area-head-text><img id="toggle-img-1" src="images/box_opener.png"/>Starterpaket</area-head-text></toggler-1>
</td></tr>
<tr><td>
<div id="toggle-content-1">
<area-head-text>
<img class="text-image" src="images/arrow.png"/>3 individuelle Entwürfe<br>
<img class="text-image" src="images/arrow.png"/>3 Korrekturzeichnungen<br>
<img class="text-image" src="images/arrow.png"/>Internationale Nutzungsrechte<br>
<img class="text-image" src="images/arrow.png"/>400€<br><br>
</area-head-text>
</div>
</td></tr>
I'm not sure why you put "Obviously" a loop doesn't work, because that's pretty much exactly what you should do. Something like this:
for(var i = 1; i <= 8; i++)
{
var div = $('#toggle-content-' + i);
var img = $('#toggle-img-' + i);
var toggler = $('toggler-' + i);
$(div).hide()
$(toggler).click(function() {
if (sliding == false) {
sliding = true;
// Open / Close
$( div ).slideToggle(time,"swing");
// ...
}
This is 2 options.
(and my preference) -
Instead of using an ID to add the click event onto each individual toggle button, use the same class on each, and add the click event on that class. When the user clicks a toggle button traverse the DOM from the clicked toggle button to perform your toggle on the relevant <div>.
This would look something like:
$(function() {
$('.toggleBtn').click(function() {
var sliding = $(this).data('sliding'); //use data attr to store sliding status
if (sliding == false) {
$(this).data('sliding') = true;
}else {
return; //don't toggle we're sliding
}
// navigate to element and toggle
$(this).parent('.someParentElement').children('.theDiv').slideToggle(time,"swing");
//clear sliding status
$(this).data('sliding', false);
}
}
The reason this is my preference, is because although it's faster to target an ID for a click event than a class for a single event, using 7 click events on 7 different IDS in my opinion (I don't know for sure) is less efficient than using a single click event on 1 class. That's my perceived purpose of using events on classes rather than IDS.
Also this way, when you want to add another box in, or remove a box, you don't need to modify any Javascript, the only thing you would need to maintain this code for is if you decide to change the structure of the HTML, and therefore the navigation of the DOM to perform your toggle.
using your method:
var ids = ["id1","id2","id3"];
for(var id in ids) {
var $div = $('#toggle-content-' + id);
var $img = $('#toggle-img-' + id);
var $toggler = $('toggler-' + id);
$div.hide()
$toggler.click(function() {
if (sliding == false) {
sliding = true;
// Open / Close
$div.slideToggle(time,"swing");
// ...
}

Need To Convert Text To UpperCase and Lowercase When Clicked

I know nothing about JavaScript, and I'm sure this is an easy thing to do, but I've been bashing my brain for the past three hours trying to figure it out.
What I want is to have some text, say Test.com, that when clicked will transform all the letters to uppercase (TEST.COM). If the user clicks again, the text will go to all lowercase(text.com). On the third click the text goes back to the original form (Test.com).
Is this possible?
var count = 1;
$('.text').click(function() {
$(this).toggleClass('uppercase', count === 2);
$(this).toggleClass('lowercase', count === 3);
if (count === 3) {
count = 0
}
count++;
});
.uppercase {
text-transform: uppercase;
}
.lowercase {
text-transform: lowercase;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<span class="text">CamelCase 1 </span>
Here's the long-winded vanilla JS version:
// grab the element containing the text
var div = document.querySelector('#test');
// grab the text
var text = div.innerHTML;
// save a copy of the text
var originalText = div.innerHTML;
// set `toggle` to O for original
// L = lowercase, U = uppercase
var toggle = 'O';
// add an click listener to the element containing the text
div.addEventListener('click', function () {
// toggle between the states updating the text
// of the element with each new click
switch (toggle) {
case 'O':
div.innerHTML = text.toUpperCase();
toggle = 'U';
break;
case 'U':
div.innerHTML = text.toLowerCase();
toggle = 'L';
break;
case 'L':
div.innerHTML = originalText;
toggle = 'O';
break;
}
}, false)
DEMO
And if you wanted to get this working for multiple instances of text on the page, something like this would work. Ideally you'd want to use event propagation for this, but since the layout of your page might change in the future it's probably not worth the risk:
;(function () {
// grab all the elements
var divs = document.querySelectorAll('.test');
// status is used to keep track of where in the cycle each text item is
var status = {};
for (var i = 0, l = divs.length; i < l; i++) {
var div = divs[i];
var key = div.innerHTML.toLowerCase();
// update the status object with the initial text values
status[key] = {
status: 'O',
originalText: div.innerHTML
};
// add the listener like last time
// except this time we monitor the status object for
// for each text instance
div.addEventListener('click', function () {
var text = this.innerHTML.toLowerCase();
var key = status[text].originalText.toLowerCase();
var toggle = status[key].status;
var originalText = status[key].originalText;
switch (toggle) {
case 'O':
this.innerHTML = originalText.toUpperCase();
status[key].status = 'U';
break;
case 'U':
this.innerHTML = originalText.toLowerCase();
status[key].status = 'L';
break;
case 'L':
this.innerHTML = status[key].originalText;
status[key].status = 'O';
break;
}
}, false);
}
}());
DEMO
Define 2 CSS classes.
.ucase {text-transform:uppercase;}
.lcase {text-transform:lowercase;}
Use a combination of jQuery .hasClass() .removeClass() and .addClass() to switch the cases.
Remove all classes from the text to return to original state.
jQuery(document).ready(function() {
jQuery(".textitem").click(function() {
$t = jQuery(this);
if($t.hasClass("ucase")) {
$t.removeClass("ucase").addClass("lcase");
} else if($t.hasClass("lcase")) {
$t.removeClass("lcase");
} else {
$t.addClass("ucase");
}
});
});
Fiddle: https://jsfiddle.net/ptj1ke8y/
Perhaps not the most elegant solution, but you can count the clicks (modulus 3), and adjust the text according to the number and cycle through your 3 cases.
var i = 0;
var cl = $('#text').text();
$('#text').click(function() {
var str = $(this).text();
if (i % 3 == 0) {
$('#text').html(str.toUpperCase());
}
if (i % 3 == 1) {
$('#text').html(str.toLowerCase());
}
if (i % 3 == 2) {
$('#text').html(cl);
}
i++
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<div id="text">Text</div>
You can use .toUpperCase() and .toLowerCase() JavaScript methods to change the case of any text.
Since you're using jQuery then you can use the .text() jQuery method to get and set the text content of any DOM node.
You need to store somewhere the original value of your text so that you can get it after the third click, and the jQuery .data() method would be good for this because that way you can easily have few elements on one page that behaves this way.
You can write something like this to make all elements with class "test" behave in a way that you have described:
$('.test').click(function () {
var $this = $(this),
data = $this.data('clicker');
if (!data || !data.text) {
data = {
text: [
$this.text(),
$this.text().toUpperCase(),
$this.text().toLowerCase()
],
step: 0
};
}
data.step = (data.step + 1) % 3;
$this.text(data.text[data.step]);
$this.data('clicker', data);
});
See: DEMO for an example of how it works with 3 elements simultaneously.
First use click() to event handler to the "click" and then use .hasClass(), removeClass() and addClass() to do and use css text-transform
HTML file
<div id="trigger">click me to transform</div>
CSS File
.uppercase { text-transform: uppercase; }
.lowercase { text-transform:lowercase; }
Javascript file
$( document ).ready(function() {
$( "#trigger" ).click(function() {
if($( "#trigger" ).hasClass( "uppercase" )) {
$(this).removeClass('uppercase').addClass('lowercase');
}
else {
$(this).removeClass('lowercase').addClass('uppercase');
}
});
});
Try to play the Sandbox
I think this is what you want (button caption changes to tell what is it going to do and changes the text):
<form name="form1" method="post">
<input name="instring" id="instring" type="text" value="this is the text string" size="30">
<input type="button" id="button" name="Convert" value="Make Uppercase >>" onClick="makeUppercase();">
<input name="outstring" type="text" id="outstring" value="" size="30">
</form>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.2/jquery.min.js"></script>
<script>
function makeUppercase(){
if( $('#button').val()=="Make Uppercase >>"){
$('#button').attr("value","Make Lowercase >>");
$('#outstring').attr('value', $('#instring').attr('value').toUpperCase());
} else if($('#button').val()=="Make Lowercase >>") {
$('#button').attr("value","Make Original >>");
$('#outstring').attr('value', $('#instring').attr('value').toLowerCase());
} else{
$('#button').attr("value","Make Uppercase >>");
$('#outstring').attr('value', $('#instring').attr('value'));
}
}
</script>

Declare a JavaScript function which can hide the label of the calling HTML element

HTML
<label for="ABC">LABEL1</label><input type="text" id="ABC" onFocus="label();"/>
<label for="DEF">LABEL2</label><input type="text" id="DEF" onFocus="label();"/>
JavaScript
I want to declare a JS function with name "label" which can find the label of the element from which it has been called and hide it.
Problem Solved! Thank you all for the support! :D
This hides the label of the corresponding input.
function focus() {
var labels = document.getElementsByTagName('label');
for(var i = 0; i < labels.length; i ++) {
var attr = labels[i].getAttribute('for'); //or labels[i].htmlFor
if(attr === this.id) {
labels[i].style.visibility = 'hidden';
//or labels[i].style.display = 'none';
}
}
}
document.getElementById('ABC').addEventListener('focus', focus);
document.getElementById('DEF').addEventListener('focus', focus);
JSFiddle
A jQuery solution:
$('input').on('focus', function() {
$('label[for=' + this.id + ']').hide();
});
+c.P.u1 jQuery solution can be written in standard JS for modern browsers (IE >=9) as follows
<label for="ABC">LABEL1</label><input type="text" id="ABC" onFocus="label(this);"/>
<label for="DEF">LABEL2</label><input type="text" id="DEF" onFocus="label(this);"/>
function label (el) {
(el = document.querySelector ('label[for=" + el.id + '"]')) &&
(el.style.display = 'none');
}
Note that we need to pass the input element as a parameter to the label function.
The fiddle at http://jsfiddle.net/jstoolsmith/v5kZb/ shows a more structured way of doing this and also replaces the label when the input element loses focus.
This is a somewhat belated solution, and applies only to more up-to-date/modern browsers (basically, not Internet Explorer before version 8). This solution implements display-toggling (hiding the label when the input is focused, restoring it when the input is blurred):
Version one, taking advantage of the DOM structure:
// gets the first 'form' element:
var parentElement = document.querySelector('form');
function labelToggle (e) {
// gets the target of the event ('e'),
// the element that was focused or blurred:
var self = e.target;
// if the element has an 'id':
if (self.id) {
// get the previous sibling element
var prev = self.previousElementSibling;
// if it's 'display: none', change display to 'inline',
// otherwise change to 'display: none':
prev.style.display = prev.style.display == 'none' ? 'inline' : 'none';
}
}
/* using event-delegation to avoid event-binding with a loop,
using event-capturing to allow for an ancestor to listen for
the 'non-bubbling' 'focus' and 'blur' events:
*/
parentElement.addEventListener('focus', labelToggle, true);
parentElement.addEventListener('blur', labelToggle, true);
JS Fiddle demo.
Version two, using the for attribute (rather than the DOM structure):
// gets the first 'form' element:
var parentElement = document.querySelector('form');
function labelToggle (e) {
// gets the target of the event ('e'),
// the element that was focused or blurred:
var self = e.target;
// if the element has an 'id':
if (self.id) {
// get the label with the relevant 'for' attribute,
// using CSS' attribute-equals notation:
var label = this.querySelector('label[for="' + self.id + '"]');
// if it's 'display: none', change display to 'inline',
// otherwise change to 'display: none':
label.style.display = label.style.display == 'none' ? 'inline' : 'none';
}
}
parentElement.addEventListener('focus', labelToggle, true);
parentElement.addEventListener('blur', labelToggle, true);
JS Fiddle demo.
Obviously you can call the relevant functions by whatever name you prefer, I call them 'labelToggle' simply because I prefer a function-name to give some indication of what that function does when it's called.
References:
document.querySelector().
document.querySelectorAll() compatibility.
element.addEventListener().
elementTraversal.previousElementSibling.
Your question is not clear, what you want to hide, label or textbox? However, here is an idea; it might help you.
<label for="ABC">LABEL1</label><input type="text" id="ABC" onFocus="label(this.id);"/>
<label for="DEF">LABEL2</label><input type="text" id="DEF" onFocus="label(this.id);"/>
function label(valID){
var totalLabel= document.getElementsByTagName('label');
for(var l = 0; l < totalLabel.length; l++) {
var lbb= totalLabel[l].getAttribute('for');
if(lbb === valID) {
labels[l].style.visibility = 'hidden';
}
}
}
Jquery will be best suited for this. Demo here
function hideLabel(element) {
var name = $(element).attr("class");
var lab = $("." + name)[0];
$(lab).hide();
}
function showLabel(element) {
var name = $(element).attr("class");
var lab = $("." + name)[0];
$(lab).show();
}
HTML
<label class="a">
Label1</label>
<input type="text" class="a" id="ABC" onfocus="hideLabel(this)" onblur="showLabel(this)" />
<label class="b">
Label2</label>
<input type="text" class="b" id="DEF" onfocus="hideLabel(this)" onblur="showLabel(this)" />

How do I remove last character from input field on click?

I have a form that when buttons are clicked, it enters a value into an input field. I want to add another button that deletes the last character added. How would I accomplish this using jQuery
<script>
function addTextTag(txt)
{
document.getElementById("text_tag_input").value+=txt;
}
function removeTextTag()
{
var strng=document.getElementById("text_tag_input").value;
document.getElementById("text_tag_input").value=strng.substring(0,strng.length-1)
}
</script>
<input id="text_tag_input" type="text" name="tags" />
<div class="tags_select">
1
2
3
delete
</div>​
Used a modified version of your code itself try
the simple answer is, if you are using jquery, to do something like this:
//select the button, add a click event
$('#myButtonId').on('click',function () {
//get the input's value
var textVal = $('#myInputId').val();
//set the input's value
$('#myInputId').val(textVal.substring(0,textVal.length - 1));
});
var lastChar = function (x) {
"use strict";
var a = document.getElementById(x),
b = a.value;
a.value = b.substring(0, b.length - 1);
};
No jQuery required. The x variable is the id of the input you want to mutilate.

Categories

Resources