jQuery fadeIn div when input is in focus? - javascript

I'm trying to change the innerHTML of a div and fade it in when a input in my form comes into focus. I also want to test whether or not it's been faded in at all because when the page loads it will begin faded out.
To summarize, I essentially want to display a tooltip in another div and switch the tooltip with fading in and out as my inputs come into focus on my form.
Here's what I have so far:
<script type="text/javascript">
var visible = 0;
var nameText = "<p>May I get your<br/>full name?</p>";
var emailText = "<p>Could I please<br/>get your email<br/>address?</p>";
var messageText = "<p>What is the<br/>message you<br/>would like to send?</p>";
$('.inp').on("focus", function(event){
if (visible == 0)
{
var fadeTime = 1;
visible = 1;
}
else
fadeTime = 500;
$('bubble').fadeOut(fadeTime).html(function() {
if ($this.attr('id') == "name")
return nameText;
else if ($this.attr('id') == "email")
return emailText;
else if ($this.attr('id') == "message")
return messageText;
}).fadeIn(500);
});
</script>
I'm not receiving any JavaScript errors. My HTML for my bubble and inputs looks like this:
<footer class="container">
<div class="row reveal">
<div class="mailman fourcol">
<img src="images/mailman.png" alt="The Mail Man" />
<div id="bubble">
</div>
</div>
<div class="contact eightcol last">
<h1>CONTACT US FOR</h1> <h1>MORE INFORMATION</h1>
<div class="clear"></div>
<form name="contact-form">
<div class="form-left">
<div class="contact-name inp">
<input type="text" name="name" id="name" value="Name" />
</div>
<div class="contact-email inp">
<input type="text" name="email" id="email" value="Email" />
</div>
<div class="clear"></div>
<div class="contact-message inp">
<input type="text" name="message" id="message" value="Message" />
</div>
</div>
<div class="contact-submit">
</div>
</form>
</div>
</div>
</footer>

I did some fix to you. Check the demo.
The main problems are:
focus event should be fired on input element, $('.inp').on("focus", function(event){ should be $('.inp').on("focus", 'input', function(event){
$this.attr(id), you missed var $this = $(this); outside, or just use var id = this.id;.
$('bubble') should be $(#bubble)

Related

I can't get past the js div hiding problem

I want to hide the divi when I click the button and open it when I click it again. But I couldn't run the normally working code, what could be the reason?
The js code works when there is only one div, but it does not work due to this code I wrote, but I can't solve the problem.
Razor Page
#for (int i = 0; i < Model.quest.Count; i++)
{
<div class="row mt-12" >
<div class="col-md-1">
<input type="checkbox" id="questcb" asp-for="#Model.quest[i].check">
<span>#(i + 1) Soru</span>
</div>
<div class="col-md-9">
<textarea class="form-control" asp-for=#Model.quest[i].Question rows="3" id="question" hidden></textarea>
<label>#Model.quest[i].Question</label>
</div>
</div>
<div class="row mt-12">
<div class="col-md-1" hidden>
<button class="btn btn-outline-secondary" type="button" id="A" onclick="clickFunc(this.id)">A</button>
</div>
<div class="col-md-1" >
A)
</div>
<div class="col-md-11" hidden="hidden">
<input type="text" asp-for=#Model.quest[i].Answer1 class="form-control" placeholder="" id="answer"
aria-label="Example text with button addon" aria-describedby="button-addon1">
</div>
<div class="col-md-11" id="Amod_#i" style="display:inline-block">
#Model.quest[i].Answer1
</div>
<div class="col-md-2">
<button class="btn btn-primary" type="button" id="mod_#i" onclick="question(this.id)">Cevapları Görüntüle</button>
</div>
</div>
}
js code
let question = button => {
let element = document.getElementById(`A${button}`);
let buttonDOM = document.getElementById(`${button}`)
let hidden = element.getAttribute("hidden");
if (hidden) {
element.removeAttribute("hidden");
buttonDOM.innerText = "Cevapları Gizle";
}
else {
element.setAttribute("hidden", "hidden");
buttonDOM.innerText = "Cevapları Görüntüle";
}
}
</script>
If the id of div is unique in your code,your js should work.If it still doesn't work,you can try to find the div with the position of the button:
let question = button => {
let element = $("#" + button).parent().siblings(".col-md-11")[1];
let buttonDOM = document.getElementById(`${button}`);
if (element.hidden) {
element.removeAttribute("hidden");
buttonDOM.innerText = "Cevapları Gizle";
}
else {
element.setAttribute("hidden", "hidden");
buttonDOM.innerText = "Cevapları Görüntüle";
}
}
result:

how dynamically add new button by javascript

I have two textboxes and one button,
I want to add one new textfield, that should show card name from textbox1 and Link URL append from textbox2 when I click on button
//AddnNewCardNavigator
var counter=2;
var nmecardtxt= document.getElementById("textbox1").value;
var linkurltxt= document.getElementById("textbox2").value;
$("#addbutton").click(function(){
if(nmecardtxt ==""||nmecardtxt ==0||nmecardtxt ==null
&& linkurltxt ==""||linkurltxt ==""|| linkurltxt ==0||linkurltxt ==null){
alert("Please insert value in Card name and Link Url textboxes and must be correct");
return false;
}
var NewCarddiv = $(document.createElement('div')).attr("id",'cardlink'+counter);
NewCarddiv.after().html()
})
</script>
<!-- text boxes-->
<div class="row">
<div class="col-md-12">
<div id="textboxesgroup">
<div id="textboxdiv1">
<label style="color:blanchedalmond">Card Name: </label><input type="textbox" id="textbox1">
</div>
<div id="textboxdiv2">
<label style="color:blanchedalmond">Link Url:    </label><input type="textbox" id="textbox2">
</div>
</div>
</div>
</div>
Your variables nmecardtxt and linkurltxt must be created inside the click function,
because it's empty at the loading of the page.
I also took the liberty to use jQuery for that variables, as you're already using it, and tried to enhance some other things:
(See comments in my code for details)
//AddnNewCardNavigator
var counter = 2;
// On click function
$("#addbutton").click(function() {
// Here it's better
var nmecardtxt = $("#textbox1").val();
var linkurltxt = $("#textbox2").val();
// Modified you test here
if (!nmecardtxt || !linkurltxt) {
alert("Please insert value in Card name and Link Url textboxes and must be correct");
return false;
}
// Modified creation of the card
var link = $(document.createElement('a')).attr("href", linkurltxt).html(linkurltxt);
var NewCarddiv = $(document.createElement('div')).attr("id", 'cardlink' + counter).html(nmecardtxt + ": ").append(link);
$('#cards').append(NewCarddiv);
//NewCarddiv.after().html(); // Was that line an attempt of the above ?
});
body {
background: #888;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<!-- text boxes-->
<div class="row">
<div class="col-md-12">
<div id="textboxesgroup">
<div id="textboxdiv1">
<label style="color:blanchedalmond">Card Name: </label><input type="textbox" id="textbox1">
</div>
<div id="textboxdiv2">
<label style="color:blanchedalmond">Link Url:   </label><input type="textbox" id="textbox2">
</div>
</div>
</div>
</div>
<!-- Added the below -->
<div id="cards">
</div>
<button id="addbutton">Add…</button>
Hope it helps.
Here's a simplified version of what you're trying to accomplish:
function addNewCard() {
var name = $('#name').val();
var url = $('#url').val();
var count = $('#cards > .card').length;
if (!name || !url) {
alert('Missing name and/or URL.');
}
var card = $('<div class="card"></div>').html("Name: " + name + "<br>URL: " + url);
$("#cards").append(card);
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<label for="name">Name:</label>
<input type="text" id="name" name="name">
<label for="url">URL:</label>
<input type="text" id="url" name="url">
<input type="submit" value="Add Card" onclick="addNewCard();">
<div id="cards">
</div>

Validation JavaScript not work in jQuery mobile

I try to validate user's input from client side using JavaScript but it not work.
First I write a validation in JavaScript file like this:
var main = function checkLomake() {
try {
var etu = $("#etu").val();
var suku = $("#suku").val();
var sposti = $("#sposti").val();
var puh = $("#puhelin").val();
var osoite = $("#osoite").val();
var etuVirhe = checkNimi(etu);
var sukuVirhe = checkNimi(suku);
var spostiVirhe = checkSposti(sposti);
var puhVirhe = checkPuh(puh);
var osoiteVirhe = checkOsoite(osoite);
if (etuVirhe === 1 && sukuVirhe === 1 && spostiVirhe === 1 && puhVirhe === 1 && osoiteVirhe === 1)
alert(getVirhe(1));
return false;
else {
if (etuVirhe !== 0) {
alert(getVirhe(checkNimi(etu)));
}
if (sukuVirhe !== 0) {
alert(getVirhe(checkNimi(suku)));
}
if (osoiteVirhe !== 0) {
alert(getVirhe(checkOsoite(osoite)));
}
if (puhVirhe !== 0) {
alert(getVirhe(checkPuh(puh)));
}
if (spostiVirhe !== 0) {
alert(getVirhe(checkSposti(sposti)));
}
return false;
}
} catch (e) {
}
};
Then I call it when user submit a form like this:
$(document).ready(function () {
$("#form-lomake").on("submit",function () {
return main();
});
});
And in HTML file I have a form like this:
<form id="form-lomake" name="form-lomake" action="uusivaraus.php" method="post">
<div data-role="collapsible" data-collapsed-icon="carat-r" data-expanded-icon="carat-d" id="coll-lomake">
<h1>Täytä tiedot</h1>
<div class="ui-field-contain">
<label for="etu">Etunimi</label>
<input type="text" id="etu" placeholder="etunimi" name="etu" data-clear-btn="true" />
<!--<p><?php print($asiakas->getVirheTeksti($nimiVirhe)); ?></p>-->
</div>
<div class="ui-field-contain">
<label for="suku">Sukunimi</label>
<input type="text" id="suku" placeholder="sukunimi" name="suku" data-clear-btn="true" />
<!--<p><?php print($asiakas->getVirheTeksti($nimiVirhe)); ?></p>-->
</div>
<div class="ui-field-contain">
<label for="osoite">Osoite</label>
<input type="text" id="osoite" placeholder="osoite" name="osoite" data-clear-btn="true" />
<!--<p><?php print($asiakas->getVirheTeksti($osoiteVirhe)); ?></p>-->
</div>
<div class="ui-field-contain">
<label for="sposti">Email</label>
<input type="text" id="sposti" placeholder="sähköposti" name="sposti" data-clear-btn="true" />
<!--<p><?php print($asiakas->getVirheTeksti($spostiVirhe)); ?></p>-->
</div>
<div class="ui-field-contain">
<label for="puhelin">Puhelin</label>
<input type="text" id="puhelin" placeholder="puhelin numero" name="puhelin" data-clear-btn="true" />
<!--<p><?php print($asiakas->getVirheTeksti($puhVirhe)); ?></p>-->
</div>
<div class="ui-field-contain">
<textarea rows="10" cols="10" placeholder="lisätietoja" name="lisatieto"></textarea>
</div>
<div class="ui-grid-b">
<div class="ui-block-a">
<input type="reset" value="Peruu" id="btn-peruuta" name="peruuta" class="ui-btn ui-corner-all ui-shadow" data-icon="delete" />
</div>
<div class="ui-block-b"></div>
<div class="ui-block-c">
<input type="submit" value="Varaa" id="btn-varaa" name="varaa" class="ui-btn ui-corner-all ui-shadow ui-btn-active" data-icon="check" data-iconpos="right" />
</div>
</div>
</div>
</form>
But I don't know why when I submit a form, it go straight to PHP file without checking user's input. Can someone help me for resolving this issue, thanks.
You are not preventing the form from being submitted, and as the form action attribute is action="uusivaraus.php", you are being redirected to the .php file when it submits. You need to prevent the default form submission before calling your function:
$(document).ready(function () {
$("#form-lomake").on("submit",function (e) {
e.preventDefault(); //this will prevent the default submission
return main();
});
Here is a working example.

How do I get a <div> on a nearby node in the DOM?

I'm trying to write some JavaScript that could be used throughout my app, and allow a checkbox to show/hide a nearby element.
If I have these elements:
<div class="optionable" style="display: block;">
<div class="row">
<div class="col-md-2">
<input checked="checked" class="form-control"
data-val="true" id="IsActive"
name="IsActive"
onclick="CheckboxOptionsToggle(this);"
type="checkbox" value="true">
</div>
<div class="col-md-8">
Chapter
</div>
</div>
<div class="row options">
<div class="col-md-12">
Some data here...
</div>
</div>
</div>
And this script:
CheckboxOptionsToggle = function (thisCheckbox) {
debugger;
var optionElement = $('.options');
if (thisCheckbox.checked) {
$(thisCheckbox).closest(optionElement).show();
} else {
$(thisCheckbox).closest(optionElement).hide();
}
}
But this isn't working. I would like the checkbox with the onclick="CheckboxOptionsToggle(this);" to trigger the options element in the same optionable div to either show or hide.
What am I doing wrong in my JavaScript/jQuery?
UPDATE: This is my final solution:
$('.optionToggle').on('change', function () {
$(this).closest('.optionable').find('.options').toggle(this.checked);
});
$(document).ready(function () {
var toggleElements = document.body.getElementsByClassName('optionToggle');
for (var i = 0; i < toggleElements.length; i++) {
var thisCheck = $(toggleElements[i]);
thisCheck.closest('.optionable').find('.options').toggle(thisCheck.prop('checked'));
}
});
<div class="optionable" style="display: block;">
<div class="row">
<div class="col-md-2">
<input checked="checked" class="form-control optionToggle"
data-val="true" id="IsActive"
name="IsActive"
type="checkbox" value="true">
</div>
<div class="col-md-8">
Chapter
</div>
</div>
<div class="row options">
<div class="col-md-12">
Some data here...
</div>
</div>
</div>
Be more generic, and stop using inline event handlers
$('[type="checkbox"]').on('change', function() { // or use class to not attach to all
$(this).closest('.optionable').find('.options').toggle(this.checked);
}).trigger('change');
FIDDLE
You can change it like
CheckboxOptionsToggle = function (thisCheckbox) {
debugger;
var optionElement = $('.options');
if (thisCheckbox.checked) {
$(thisCheckbox)..closest('div.optionable').find(optionElement).show();
} else {
$(thisCheckbox)..closest('div.optionable').find(optionElement).hide();
}
}
I would stay away from .closes, because it is so specific, instead I would go with more reusable code like so:
HTML:
<input type="checkbox" id="toggler" data-target-class="some-div" class="toggler" value="myValue" checked> Toggle Me
<div class="some-div">
Some Text within the div.
</div>
JS:
$('#toggler').on('click', function() {
var targetClass = $(this).data('target-class');
$('.' + targetClass).toggle($(this).checked);
});
JSFiddler: https://jsfiddle.net/ro17nvbL/
I am using data element on the checkbox to specifiy which divs to show or hide. This allows me to not only hide/show divs but anything n the page, and not only one instance but as many as needed. Way more flexible - still does the same job.

Clone elements and add into mark-up code so form submission picks them up

When the clone button is clicked, size and length fields should be cloned and placed below. Crucial point is, I should be able to see these cloned mark-up code when I check the browser source code because I'll submit all fields.
HTML
<style>
div { display:inline-block; }
.needles, .yarns, .options { border:1px solid #14A; padding:10px; }
</style>
<div class='needles'>
<p>NEEDLES</p>
<div class='options'>
<div class='label'>Size</div>
<div class='field'>
<input id='size-0' name='size-0' value='Size' />
</div>
</div>
<br />
<div class='options'>
<div class='label'>Length</div>
<div class='field'>
<input id='length-0' name='length-0' value='Length' />
</div>
</div>
<br /><br />
<button>Clone</button>
</div>
<br />
<div class='yarns'>
<p>YARNS</p>
<div class='options'>
<div class='label'>Size</div>
<div class='field'>
<input id='size-0' name='size-0' value='Size' />
</div>
</div>
<br />
<div class='options'>
<div class='label'>Length</div>
<div class='field'>
<input id='length-0' name='length-0' value='Length' />
</div>
</div>
<br /><br />
<button>Clone</button>
</div>
I did something like this but I think it is a mess to be honest.
$("button").click(function(event) {
event.preventDefault();
var $parent = $(this).closest('div');
var $length = $parent.prev();
var $size = $length.prev();
var size = $size.clone(false).wrap('<p>').parent().html();
var length = $length.clone(false).wrap('<p>').parent().html();
var spanId = $(size).children('span').attr('id');
var idArray = spanId.split("__");
var currentIdentifierNo = idArray[idArray.length-2];
var newIdentifierNo = parseInt(currentIdentifierNo)+1;
var currentIdentifier = '__' + currentIdentifierNo + '__';
var newIdentifier = '__' + newIdentifierNo + '__';
var re = new RegExp(currentIdentifier, 'g');
size = size.replace(re, newIdentifier);
length = length.replace(re, newIdentifier);
var html = size + length;
$(this).before(html);
});
You have to change the name attribute for this to work:
length.find('input').attr('name', 'length-1');
size.find('input').attr('name', 'size-1');
If you send the same key / value pairs in the form, the server doesn't know which is which.

Categories

Resources