I am new to JavaScript. I have made a form and taken textarea and button and displayed the text of the textarea in a div tag and have taken 2 buttons.
Now I want on click of first button the size of output in div tag increase and similarly on click of second button it becomes bold and so on ...
<html>
<body>
<form name="myform" onsubmit="return fuc1()">
<table>
<tr><td>Description</td><td> <textarea name="message1" id="message" rows="10" cols="30" font-size:"100px";></textarea><br/></td></tr>
<tr><td><button onclick=fincrease() type="button" name="sizeinc" id="sizeinc" >Increase SIZE</button></td>
<td><button type="button" name="sizedec" id="sizedec" >Decrease SIZE</button></td></tr>
<tr><td><button type="button" onclick="fbold()" name="bold" id="bold" >BOLD</button></td>
<td><button type="button" name="italic" id="italic" >ITALIC</button></td>
<td><button type="button" name="underline" id="underline" >UNDERLINE</button></td></tr>
<tr><td><select id="colors" onclick="fcolor()">
<option value="Default">(Please select color)</option>
<option value="pink">PINK</option>
<option value="yellow">YELLOW</option>
<option value="green">GREEN</option>
<option value="orange">ORANGE</option>
</select>
</td>
<td><select id="borders" onclick="fborder()">
<option value="Default">(Please select border)</option>
<option value="dashed">DOTTED</option>
<option value="thick solid">Thick Solid</option>
<option value="solid">Solid</option>
</select></td>
</tr>
<tr><td><input type="submit"/></td></tr>
</table>
<div id="div1">OUTPUT</div>
</form>
<script type="text/javascript">
function fuc1()
{
var tex=document.getElementById("message").value;
var colr=document.getElementById("colors").value;
var bord=document.getElementById("borders").value;
var increase=document.getElementById("sizeinc").value;
var decrease=document.getElementById("sizedec").value;
var italic1=document.getElementById("italic").value;
var bold1=document.getElementById("bold").value;
var under=document.getElementById("underline").value;
html=tex;
document.getElementById("div1").innerHTML=html;
return false;
}
function fcolor(){
var c=document.getElementById("colors").value;
if(c=="pink")
{
document.getElementById("div1").style.color= c;
}
if(c=="yellow")
{
document.getElementById("div1").style.color= c;
}
if(c=="green")
{
document.getElementById("div1").style.color= c;
}
if(c=="orange")
{
document.getElementById("div1").style.color= c;
}
}
function fborder(){
var b=document.getElementById("borders").value;
if(b=="dashed")
{
document.getElementById("div1").style.border=b;
}
if(b=="thick solid")
{
document.getElementById("div1").style.border=b;
}
if(b=="solid")
{
document.getElementById("div1").style.border=b;
}
}
function fbold()
{
}
</script>
Remember to add them to the onclick events of your buttons
function fbold()
{
if (document.getElementById("div1").style.fontWeight == "bold")
{
document.getElementById("div1").style.fontWeight = "normal"
}
else
{
document.getElementById("div1").style.fontWeight = "bold";
}
}
function fItalic() {
if (document.getElementById("div1").style.fontStyle == "italic") {
document.getElementById("div1").style.fontStyle = "normal"
}
else {
document.getElementById("div1").style.fontStyle = "italic";
}
}
function fUnderline()
{
if (document.getElementById("div1").style.textDecorationUnderline) {
document.getElementById("div1").style.textDecorationUnderline = false
}
else {
document.getElementById("div1").style.textDecorationUnderline = true;
}
}
function fincrease()
{
if (document.getElementById("div1").style.fontSize == undefined || document.getElementById("div1").style.fontSize == "")
{
document.getElementById("div1").style.fontSize = "14px"
}
document.getElementById("div1").style.fontSize = (Number(document.getElementById("div1").style.fontSize.replace("px", "")) + 1) + "px"
}
function fdecrease() {
if (document.getElementById("div1").style.fontSize == undefined || document.getElementById("div1").style.fontSize == "") {
document.getElementById("div1").style.fontSize = "14px"
}
document.getElementById("div1").style.fontSize = (Number(document.getElementById("div1").style.fontSize.replace("px", "")) - 1) + "px"
}
General tip: add some console.log("...") messages to your functions and open your page in a browser that has a console (e.g. in Google Chrome, press F12). That will enable you to see when a function is called while you test it.
More specific tip: on the select lists, replace onclick with onchange.
Related
I am trying to retain div on exiting a page and am not very sure how to go about this, I am aware that I can achieve this using localStorage but cannot figure out how, here is the script
<script type="text/javascript">
function ShowHideDiv() {
var ddlPassport = document.getElementById("ddlPassport");
var dvPassport = document.getElementById("dvPassport");
dvPassport.style.display = ddlPassport.value == "Y" ? "block" : "none";
var ddlPassport = document.getElementById("ddlPassport");
var dvPassports = document.getElementById("dvPassports");
dvPassports.style.display = ddlPassport.value == "N" ? "block" : "none";
}
</script>
<span>Do you have Passport?</span>
<select id = "ddlPassport" onchange = "ShowHideDiv()">
<option value="N">No</option>
<option value="Y">Yes</option>
</select>
<!--<hr />-->
<div id="dvPassport" style="display: none">
Passport Number:
<input type="text" id="txtPassportNumber" />
</div>
<div id="dvPassports" style="display: none">
Other Number:
<input type="text" id="txtPassportNumbers" />
</div>
thank you very much for your help!
In the beforeunload of the window object, set whatever you like into localStorage.
Also, it's better to use CSS classes than to apply individual style properties.
window.addEventListener("DOMContentLoaded", function(){
var ddlPassport = document.getElementById("ddlPassport");
var dvPassport = document.getElementById("dvPassport");
var dvPassports = document.getElementById("dvPassports");
var passNum = document.getElementById("txtPassportNumber");
var passNums = document.getElementById("txtPassportNubmers");
ddlPassport.addEventListener("change", ShowHideDiv);
// Restore prior saved data:
if(localStorage.getItem("passportNumber")){
passNum.value = localStorage.getItem("passportNumber");
ShowHideDiv();
} else if(localStorage.getItem("passportNumbers")) {
passNums.value = localStorage.getItem("passportNumbers");
ShowHideDiv();
}
var numElement = null;
function ShowHideDiv() {
if(this.value === "y"){
dvPassport.classList.remove("hidden");
dvPassports.classList.add("hidden");
numElement = dvPassport;
} else if(this.value === "n") {
dvPassport.classList.add("hidden");
dvPassports.classList.remove("hidden");
numElement = dvPassports;
} else {
dvPassport.classList.add("hidden");
dvPassports.classList.add("hidden");
}
}
// As the user is leaving the page, store the text value:
window.addEventListener("beforeunload", function(){
if(numElement === dvPassport){
localStorage.setItem("passportNumber", passNum.value);
} else if(numElement === dvPassports) {
localStorage.setItem("passportNumbers", passNums.value);
}
});
});
.hidden { display:none; }
<span>Do you have Passport?</span>
<select id = "ddlPassport">
<option value="">--- Select ---</option>
<option value="n">No</option>
<option value="y">Yes</option>
</select>
<div id="dvPassport" class="hidden">
Passport Number:
<input type="text" id="txtPassportNumber">
</div>
<div id="dvPassports" class="hidden">
Other Number:
<input type="text" id="txtPassportNumbers">
</div>
I'm trying to change the option color base on an if statment. This is my form:
function myFunction() {
var lia = document.createElement("h5");
var lib = document.createElement("p");
var item = document.getElementById('task').value;
var pro = document.getElementById('priority').value;
var item_list = document.createTextNode(item);
var item_pro = document.createTextNode(pro);
lia.appendChild(item_list);
lib.appendChild(item_pro);
document.getElementById("result").appendChild(lia);
document.getElementById("priorit").appendChild(lib);
if (pro == 'Urgent') {
$("p").css('color', 'red');
}
if (pro == 'Critical') {
$("p").css('color', 'orange');
}
if (pro == 'Normal') {
$("p").css('color', 'green');
}
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input id="task" type="text" />
<select id="priority">
<option id="Urgent">Urgent</option>
<option id="Critical">Critical</option>
<option id="Normal">Normal</option>
</select>
<button onclick="myFunction()">Add</button>
<h3>List Result</h3>
<table>
<th id="result"></th>
<th id="priorit"></th>
<table>
This if statement its what i want to do. but for now, any time im adding to the list another item with other option, all the colors are change to the last one.
you can see my problem here:
https://jsbin.com/selenifepa/edit?html,js,output
what should i do?
Use the :last-child css selector.
See this code
function myFunction() {
var lia = document.createElement("h5");
var lib = document.createElement("p");
var item = document.getElementById('task').value;
var pro = document.getElementById('priority').value;
var item_list = document.createTextNode(item);
var item_pro = document.createTextNode(pro);
lia.appendChild(item_list);
lib.appendChild(item_pro);
document.getElementById("result").appendChild(lia);
document.getElementById("priorit").appendChild(lib);
if(pro=='Urgent'){
$("p:last-child").css('color','red');
}
if(pro=='Critical'){
$("p:last-child").css('color','orange');
}
if(pro=='Normal'){
$("p:last-child").css('color','green');
}
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input id="task" type="text"/>
<select id="priority">
<option id="Urgent">Urgent</option>
<option id="Critical">Critical</option>
<option id="Normal">Normal</option>
</select>
<button onclick="myFunction()">Add</button>
<h3>List Result</h3>
<table>
<th id="result"></th>
<th id="priorit"></th>
<table>
Instead of selecting all paragraph elements, you can select added element like this:
if(pro=='Urgent'){
$(lib).css('color','red');
}
if(pro=='Critical'){
$(lib).css('color','orange');
}
if(pro=='Normal'){
$(lib).css('color','green');
}
Replace your if with this one and this is it...
The issue is because the $('p') selector matches all existing p elements in the DOM, not just the one you added. You can fix that by using $(lib) to affect only the newly added p tag.
$(lib).css('color', 'green');
However, I would also suggest you look in to using unobtrusive event handlers as on* event attributes are considered outdated. As you're already using jQuery, here's how to do that:
$('#add').click(function(e) {
e.preventDefault();
var pro = $('#priority').val();
var $lia = $("<h5 />").text($('#task').val()).appendTo('#result');
var $lib = $("<p />").text(pro).appendTo('#priorit');
if (pro == 'Urgent') {
$lib.css('color', 'red');
}
if (pro == 'Critical') {
$lib.css('color', 'orange');
}
if (pro == 'Normal') {
$lib.css('color', 'green');
}
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input id="task" type="text" />
<select id="priority">
<option id="Urgent">Urgent</option>
<option id="Critical">Critical</option>
<option id="Normal">Normal</option>
</select>
<button id="add">Add</button>
<h3>List Result</h3>
<table>
<th id="result"></th>
<th id="priorit"></th>
<table>
The reason is that you are selecting all the p tags with $('p'). Also, you have mixed jQuery with vanilla JS. I'll assume you want to use jQuery to simplify your code. Here it goes.
function add() {
// select the elements and assign to a var, that way we don't have to be selecting the elements over and over, which is 'slow' (research "Why traversing the DOM is slow")
var results = $('#results'),
task = $('#task'),
priority = $('#priority'),
// create the new div element with it's content
newResult = $('<div>'+task.val()+' '+priority.val()+'</div>');
// Decide what color to apply
if(priority.val() == 'Urgent'){
newResult.css('color','red');
}
if(priority.val() == 'Critical'){
newResult.css('color','orange');
}
if(priority.val() == 'Normal'){
newResult.css('color','green');
}
// append the new div to the list of results
results.append(newResult);
// clear the input and focus the cursor for the next value to be added
task.val('').focus();
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input id="task" type="text"/>
<select id="priority">
<option id="Urgent">Urgent</option>
<option id="Critical">Critical</option>
<option id="Normal">Normal</option>
</select>
<button onclick="add()">Add</button>
<h3>List Result</h3>
<div id="results"></div>
Here This should do the trick
function myFunction() {
var lia = document.createElement("h5");
var lib = document.createElement("p");
var item = document.getElementById('task').value;
var pro = document.getElementById('priority').value;
var item_list = document.createTextNode(item);
var item_pro = document.createTextNode(pro);
lia.appendChild(item_list);
lib.appendChild(item_pro);
if(pro=='Urgent'){
lia.style.color='red';
lib.style.color='red';
}else{
lia.style.color='orange';
lib.style.color='orange';
}
document.getElementById("result").appendChild(lia);
document.getElementById("priorit").appendChild(lib);
document.getElementById('task').value = '';
}
The only issue was that you're selectin all the p elements by $("p"). You need to just select the currently added element i.e. lib. But lib is a javascript variable, so wrap it in jQuery to convert it into a jQuery object and then apply jQuery css.
e.g. $(lib).css('color', 'red');
function myFunction() {
var lia = document.createElement("h5");
var lib = document.createElement("p");
var item = document.getElementById('task').value;
var pro = document.getElementById('priority').value;
var item_list = document.createTextNode(item);
var item_pro = document.createTextNode(pro);
lia.appendChild(item_list);
lib.appendChild(item_pro);
document.getElementById("result").appendChild(lia);
document.getElementById("priorit").appendChild(lib);
if (pro == 'Urgent') {
$(lib).css('color', 'red');
}
if (pro == 'Critical') {
$(lib).css('color', 'orange');
}
if (pro == 'Normal') {
$(lib).css('color', 'green');
}
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input id="task" type="text" />
<select id="priority">
<option id="Urgent">Urgent</option>
<option id="Critical">Critical</option>
<option id="Normal">Normal</option>
</select>
<button onclick="myFunction()">Add</button>
<h3>List Result</h3>
<table>
<th id="result"></th>
<th id="priorit"></th>
<table>
I made two linked drop down menus with ajax and php. My index.php:
<html>
<head>
</head>
<body>
<form name="form1" action="submit.php" method='POST'>
<select name="country" onchange="window.getStates()">
<option> Select Country</option>
<option value="pakistan">Pakistan</option>
<option value="india">India</option>
<option value="usa">USA</option>
<option value="uk">UK</option>
</select>
<input type="text" id="area" style="display: none;" size="16" placeholder="
Enter value"></input>
<input type="submit" id="submit" style="display: none" name="submit" value="submit">
</form>
<script type="text/javascript">
function show() {
{
document.getElementById('area').style.display = 'inline-block';
document.getElementById('submit').style.display = 'inline-block';
}
}
function getStates() {
var xmlhttp;
try {
xmlhttp = new XMLHttpRequest;
} catch (e) {
xmlhttp = new ActiveXObject("Microsoft.XMLHTTP");
}
if (xmlhttp) {
var form = document['form1'];
var country = form['country'].value;
xmlhttp.open("GET", "http://localhost/getStates.php?country=" + country, true);
xmlhttp.onreadystatechange = function() {
if (this.readyState == 4) {
var s = document.createElement("select");
s.onchange = show();
s.name = "state";
s.innerHTML = this.responseText;
if (form['state']) {
form.replaceChild(s, form['state']);
} else
form.insertBefore(s, form['submit']);
}
}
xmlhttp.send(null);
}
}
</script>
</body>
</html>
my getStates.php code:
<?php
$states=array(
"pakistan" => array("NWFP","Sindh","Bala","Punjab"),
"india" => array("delhi","gujrat","goa","U.P."),
"usa" => array("bgjs","hhtrs","Bhtrshts","Utah"),
"uk" => array("England","Scotland","Bahwgla","Punthwthjab")
);
if(isset($_GET['country']))
{
$c = $_GET['country'];
if(isset($states[$c]))
{
for($i = count($states[$c]) -1; $i>=0; $i--)
{
echo "<option value='".$states[$c][$i]."'>".$states[$c][$i]."</option>";
}
}
}
?>
In the index.php, when i select an option from the second drop down, i want the text box and submit button to be made divisible. How can i do this in a simple way? Please be clear and slow because i am new to ajax.
s.onchange=show();
is not working. That was just a random try but i don't know why it is wrong. Thanks!
In my HTML form, there are 2 textbox and one dropdown.
While loading the page, dropdown should not be editable(ie: disabled)
After filling all the textbox,the dropdown should be editable.
Please give an idea to solve this in javascript.
Try like this
HTML
<input type="text" id="text1" onblur="myFunction()">
<input type="text" id="text2" onblur="myFunction()">
<select id="select1" disabled>
<option>value</option>
</select>
Javascript
function myFunction() {
if (document.getElementById("text1").value.length > 0 && document.getElementById("text2").value.length > 0) {
document.getElementById("select1").disabled = false;
} else {
document.getElementById("select1").disabled = true;
}
}
Check both input elements value whenever keyup event is fired. If both the input elements have no inputs then disable the select element. Else enable it. Try this way,
javaScript :
function SetControlState(){
for(var i = 0; i < inputs.length; i++){
if(inputs[i].value.length == 0){
selectddl.disabled = true;
break;
} else{
selectddl.disabled = false;
}
}
}
var selectddl = document.getElementById("dropdl");
var inputs = document.getElementsByTagName('input');
var isEnabled = false;
for(var i = 0; i < inputs.length; i++){
if(inputs[i].id == 'first' || inputs[i].id == 'second'){
inputs[i].onkeyup = function(){
SetControlState();
};
}
}
HTML :
<select name="ddl" id="dropdl" disabled="true">
<option value="A">A</option>
<option value="B">B</option>
</select>
<input type="text" id="first"/>
<input type="text" id="second"/>
jsFiddle
http://liveweave.com/EvfTww
I have two radio buttons one says div, and another says remove.
I add in some divs in html and when I select remove I want to be able to remove divs inside of #canvas when clicked.
The function provided below only works when divs are already visible when checked, but when I add new divs in the canvas from the code editor I also want to be able to remove those as well.
Any help is greatly appreciated.
HTML
<table id="main" border="1">
<tr>
<td id="canvas" valign="top"></td>
<td valign="top">
<div id="control_box">
<form id='tools'>
<input name="tool" id="tool-1" checked="checked" type="radio">
<label for="tool-1">DIV</label>
<input name="tool" id="tool-2" type="radio">
<label for="tool-2">Remove</label>
</form><br>
Border Width <select id="divborder">
<option value="1px">1px</option>
<option value="2px">2px</option>
<option value="3px" selected="selected">3px</option>
<option value="5px">5px</option>
<option value="7px">7px</option>
<option value="8px">8px</option>
<option value="9px">9px</option>
<option value="10px">10px</option>
</select><br>
Border Style <select id="divborderstyle">
<option value="dotted">dotted</option>
<option value="dashed">dashed</option>
<option value="solid" selected="selected">solid</option>
<option value="double">double</option>
<option value="groove">groove</option>
<option value="ridge">ridge</option>
<option value="inset">inset</option>
<option value="outset">outset</option>
</select><br>
Border Color
<input id="bcolor" type="text" name="bcolor" value="#f00" /></div><br>
BG Color
<input id="bgcolor" type="text" name="bgcolor" value="#000" onchange="window.set_fill_color(this.value); var col = this.value ; $('#colorSelectorFill').ColorPickerSetColor(col);" /></div>
<input type="button" id="nobg" value="none">
</div><br><br>
<textarea id='code' placeholder="The #canvas acts as page body"></textarea>
</td>
</tr>
</table>
JQuery/JavaScript
$('#tool-2').change(function() {
if ($(this).is(':checked')) {
alert('Remove Tool Chosen! You can now remove divs within the canvas.');
$('#canvas div').on('click', function() {
$(this).remove();
code.val(preview.html());
});
} else {
alert('Houston we have a problem!');
}
});
Try something like;
<input type="radio" name="test" value="div" checked> div
<input type="radio" name="test" value="remove"> remove
$("input[#name='test']").change(function(){
$("#parent_div_id").hide();
});
http://liveweave.com/lXdfqr
Using basically the same function as before, but this time I put it in another function called canvastools, and I removed the else statement as I do not need that for this experiment.
function canvastools(e) {
if ($('#tool-2').is(':checked')) {
$('#canvas div').on('click', function() {
$(this).remove();
code.val(preview.html());
});
}
}
I then call the function by stating that when the document is changed it will call the function.
$(document).change(function(e) {
canvastools(e);
});
I found that using the select element is a bit easier, however it's not exactly isolated. The remove tool's function will still apply even when a another tool/option is selected. I haven't figured out how to fix that problem just yet.
Here's the new fiddle/weave - http://liveweave.com/e5Efnc
function wrappertools(e) {
// Tools
$("select#tools").each(function() {
// DIV Tool
if ($(this).val() === 'div') {
$('#divoptions').show();
$('#spanoptions').hide();
// No Background Option
$('#nobg').click(function() {
$('input[name=bgcolor]').val('none');
});
var bcolor = $('input[name=bcolor]').val(),
bgcolor = $('input[name=bgcolor]').val(),
divborderstyle = $('#divborderstyle').val(),
divborder = $('#divborder').val();
alert('DIV Tool Selected!');
}
// Text Tool
if ($(this).val() === 'text'){
$('#spanoptions').show();
$('#divoptions').hide();
alert('Text Tool Selected!');
// No Background Option
$('#nospanbg').click(function() {
$('input[name=spanbgcolor]').val('none');
});
$('#addspantext').on('click', function() {
var spanbcolor = $('input[name=spanbcolor]').val(),
spanbgcolor = $('input[name=spanbgcolor]').val(),
spanborderstyle = $('#spanborderstyle').val(),
spanborder = $('#spanborder').val(),
spanfont = $('#spanfont').val(),
spancolor = $('#spancolor').val(),
spansize = $('#spansize').val(),
spantext = $('#spantext').val(),
placespan = $('<span style="position: relative; font-family: ' + spanfont + '; font-size: ' + spansize + '; font-color: ' + spancolor + '; border: ' + spanborder + ' ' + spanborderstyle + ' ' + spanbcolor + '; background: '+ spanbgcolor +';">' + spantext + '</span>');
$('.wrapper').append(placespan);
code.val(preview.html());
});
return false;
}
// Remove Tool
if ($(this).val() === 'remove') {
alert('Remove Tool Selected!');
$('#divoptions').hide();
$('#spanoptions').hide();
$('.wrapper div, .wrapper span').on('click', function() {
$(this).remove();
code.val(preview.html());
});
return false;
}
});
}
$(document).ready(function(e) {
wrappertools(e);
});
$(document).change(function(e) {
wrappertools(e);
});