Supply new code to a DIV if content within it is removed - javascript

I wonder if it's possible in jQuery/JS:
If “foobar” is removed or gone from the HTML code
<div id="foo">
<div id="line1">...</div>
<div id="line2">foobar</div>
</div>
I'd like to automatically add “new”
<div id="foo">
<div id="line1">...</div>
<div id="line2">new</div>
</div>
I'd like to have "new" displayed when someone deleted "foobar" from #line2. It's for attribution purposes.

If you make the text the value of an input you can bind to it's change event:
<div id="foo">
<div id="line1">...</div>
<div id="line2"><input type="text" value="foobar" /></div>
</div>
$('#line2').children('input').on('change', function () {
var $this = $(this);
if ($this.val() == '') {
$this.val('new');
}
});
Here is a demo: http://jsfiddle.net/u9Twu/
Note that if you want to programatically change the value of the input you have to manually call .trigger('change') on the input after you change it's value for the change event handler to run.
Also note that .on() is new in jQuery 1.7 and in this case is the same as .bind().
UPDATE
var $foo = $('#foo'),
$line2 = $foo.children('#line2');
if ($line2.length == 0) {
//no #line2 element is found
$foo.append('<div id="line2">new</div>');
} else if ($line2.text().length == '') {
//#line2 element is empty
$line2.text('new');
} else if ($line2.text() != 'foobar') {
//#line2 element does not contain only the string: foobar
$line2.text('new');
}
Here is a demo: http://jsfiddle.net/u9Twu/1/

$('#foo').click(function() {
$('#line2').remove();
$(this).append('<div id="line3">new foobar</div>');
})
http://jsfiddle.net/y5FDs/

Related

If an input has a value, specific radio button should be checked

I want to check if an input (name="companyname") has a value and if so, it should check a radio button (id="Zakelijk"). If it does not have any value, it should check the other radio button (id="Particulier").
See my current code:
<script type="text/javascript">
function ShowHideDiv() {
var chkYes = document.getElementById("Zakelijk");
var dvPassport1 = document.getElementById("checkzakelijk");
var dvPassport2 = document.getElementById("checkzakelijk1");
var dvPassport3 = document.getElementById("checkzakelijk2");
var display = chkYes.checked ? "block" : "none";
dvPassport1.style.display = display;
dvPassport2.style.display = display;
dvPassport3.style.display = display;
}
</script>
<div class="col-md-12 check-business">
<div class="form-group form-group-xl">
<label for="Particulier"><input type="radio" id="Particulier"checked="checked" name="checkzakelijk" onclick="ShowHideDiv()" />Particulier</label>
<label for="Zakelijk"><input type="radio" id="Zakelijk" name="checkzakelijk" onclick="ShowHideDiv()" />Bedrijf</label>
</div>
</div>
<div class="col-md-12" id="checkzakelijk" style="display:none;">
<div class="form-group">
<label for="inputCompanyName" class="control-label">{$LANG.clientareacompanyname}</label>
<input type="text" name="companyname" id="inputCompanyName" value="{$clientcompanyname}"{if in_array('companyname', $uneditablefields)} disabled="disabled"{/if} class="form-control" />
</div>
</div>
There are other ways, but this should get you going:
$(function() {
if (($("#inputCompanyName").val() || "") != "")
{
$("#Zakelijk").prop("checked", true)
} else {
$("#Particulier").prop("checked", true)
}
});
This is based on your html where the input name='companyname' also has id 'inputCompanyName' and will clear the other radio because they have the same name=
Edit Working jsfiddle: https://jsfiddle.net/76x42os0/4
change input value in the code box (top left) and click run.
Update: Updated the fiddle to the indicated jquery version 3.1.0 and found the newer version of jquery needs id= to match #, while before it matched on name=
If you want to check it when the input is changed you can do
$("input[name='companyname']").change(function(){
var hasValue = $(this).val() === "";
$("#Zakelijk").prop("checked", hasValue);
$("#Particulier").prop("checked", !hasValue);
})
you can optimize the code, but this is more readable.
In case you need the solution in Javascript
if(document.getElementById("inputCompanyName").value !== ""){
document.getElementById("Zakelijk").checked = true;
document.getElementById("Particulier").checked = false;
}
else{
document.getElementById("Particulier").checked = true;
document.getElementById("Zakelijk").checked = false;
}
Here's a working example of what you're after (albeit without your HTML ids/layout in mind, but you can simply change the IDs within).
$("#text-box").on('change', function(){
if($(this).val() != ""){
$('#rd1').prop("checked", true)
}else{
$('#rd2').prop("checked", true)
}
});
https://jsfiddle.net/bm18hmLa/3/
It hooks into the changed event, so it would occur every time the text-box value has been changed.
After thought:
Changing
$("#text-box").on('change', function(){
to
$("#text-box").on('input', function(){
makes it a little "nicer" in terms of responsiveness.
https://jsfiddle.net/bm18hmLa/5/
and here's a version with your ID names too.
https://jsfiddle.net/bm18hmLa/6/

How would I find the label's child? (HTML + JS)

How would I make JS find the child with the class of "money"? I have it coded so that it will find the radio button when clicked. Once it's clicked it will return that radio button and id. But I also need to find the "money" class.
HTML:
<div class="col-sm-4 col-md-2">
<input name="STORAGE" type="radio" id="STORAGE2">
<label class="radio" for="STORAGE2">
<center>
<img src="../images/Parts/Western_Digital_Caviar_Blue_320GB.png" class="comp-img"><br><br>
<p>500GB Western Digital WD5000AAKX 3.5" 7200RPM HDD</p>
<p class="money">+$55</p> <!--THIS IS THE CLASS I AM TRYING TO GET-->
</center>
</label>
</div>
JS:
$(function(){
var cpu = "";
//Controling radio buttons
$('radio').on('click'), function(){
var clickedID = $(this).attr("id");
if (clickedID.substring(1,3) == "CPU") {
if (cpu == "") {
cpu = clickedID;
} else {
}
}
}
});
if your label's for attribute is the value of the radio ID then you can do like this
var el = $('label[for='+clickedID +']').find('.money');
use the jQuery find function $(this).find(".money");
Your syntax is off a little bit, but this should work:
EDIT:
As #empiric has noted, .money is not a child of $('radio'), it is a child $('.radio'), which is not the intended click target.
$('.radio').on('click', function(){
var $this = $(this);
var clickedID = $this.attr("for");
// Child .money element (put this wherever you need it)
var childMoneyEl = $this.find('.money')
if (clickedID.substring(1,3) == "CPU") {
if (cpu == "") {
cpu = clickedID;
}else{
}
}
});

set new element into list with jquery

i try to add a new li element into the list with jquery.
In this example it´s work fine, but when i want to get the value of a input field
with .val() it´s not create a li element.
http://www.w3schools.com/jquery/tryit.asp?filename=tryjquery_html_append
my code: http://jsfiddle.net/k1acpxtp/
$(document).ready(function(){
/* Click Event für Button "btn2" */
$('#btn2').click(function(){
/* Fügt ein Elemente in die Liste mit ".append" und
mit ".val()", wird das Value des Input Feldes ausgelesen */
$("ol").append($("#test").val());
});
});
Just change the code to this :
$("ol").append("<li>"+$("#test").val()+"</li>);
You're appending text to an ol element, which is invalid. You need to first create the li, set its text then append that to the ol:
$('#btn2').click(function () {
$('<li />', { text: $('#test').val() }).appendTo('ol');
});
Example fiddle
try with this code( change code where you append value in ol )
$("ol").append("<li>"+$("#test").val()+"</li>);
Use this code instead
$("ol").append("<li>"+$("#test").val()+"</li>);
Try this
$('#btn2').click(function(){
$("ol").append('<li>'+$("#test").val()+'</li>');
});
Working Demo
I'd suggest the following:
$(document).ready(function() {
$('#btn2').click(function(e) {
// preventing the default behaviour of the <button>:
e.preventDefault();
var entered = $('#test').val(),
tag;
// naive check to see if the user entered 'proper' HTML, eg:
// <li>, <li>Some content</li> etc:
if (entered.indexOf('<') === 0 && entered.lastIndexOf('>') === (entered.length - 1)) {
tag = entered;
} else {
// otherwise, if they entered 'li', 'LI' etc, we
// wrap the entered-value with the '<' and '>' to
// form an HTML tag:
tag = '<' + entered + '>';
}
// creating the element, then appending it to
// the <ol>:
$(tag).appendTo('ol');
});
});
$(document).ready(function() {
$('#btn2').click(function(e) {
e.preventDefault();
var entered = $('#test').val(),
tag;
if (entered.indexOf('<') === 0 && entered.lastIndexOf('>') === (entered.length - 1)) {
tag = entered;
} else {
tag = '<' + entered + '>';
}
$(tag).appendTo('ol');
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<ol></ol>
<form method="post" action="create.html">New Track:
<input type="text" id="test" name="track" placeholder="<tagName>" />
</form>
<button id="btn2">Add Element</button>
Note that I've also added a placeholder attribute to provide guidance for filling in the <input />.
Note that this also does not check validity of the elements you're adding; therefore it will allow you, or your users, to append a <div> to the <ol>, regardless of that action creating invalid HTML.
It may be worth adjusting so that the <li> is created automatically, but the content is supplied by the users:
$(document).ready(function() {
$('#btn2').click(function(e) {
e.preventDefault();
var entered = $('#test').val();
// creating an <li> element:
$('<li>', {
// taking the entered-value to set the element's
// innerHTML:
'html': entered
}).appendTo('ol');
});
});
$(document).ready(function() {
$('#btn2').click(function(e) {
e.preventDefault();
var entered = $('#test').val();
$('<li>', {
'html': entered
}).appendTo('ol');
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<ol></ol>
<form method="post" action="create.html">New Track:
<input type="text" id="test" name="track" placeholder="new content" />
</form>
<button id="btn2">Add Element</button>
References:
appendTo().
event.preventDefault().

Javascript, amend elements after clone

Im trying to post a cloned section of a form but it doesnt submit all due to element names being identical.
Does anyone know the best process for changing input name attributes during a clone ?
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<script>
$(document).ready(function(){
$("button").click(function(){
if (checkMACAddress()==true) {
$("#test").clone().insertAfter("div.test-row:last");
}
});
});
function checkMACAddress() {
var valid = true;
for ( var i = 0, l = document.getElementsByName("mac").length; i < l; i++ ) {
var macAddress=document.getElementsByName("mac")[i].value;
var macAddressRegExp=/^(?:[0-9A-F]{2}[:]?){5}(?:[0-9A-F]{2}?)$/i;
if (macAddressRegExp.test(macAddress)==false) { //if match failed
alert("MAC Invalid - Must be IEEE.802 example 00:3F:00:10:00:2C");
valid=false;
}
}
return valid;
}
</script>
<h3>Account Details</h3>
<div class="row">
<div class="columns small-4">
<label>Destination Account Number*</label>
[[input||type=text||name=Account||name_literal=Account||placeholder=12345||required=required]]
</div>
</div>
<hr>
<h3>Device Details</h3>
<h5>
<button type='button'>Add Device</button>
</h5>
<div id="test" class="test-row">
<div class="columns small-3">
<label>MAC - IEEE.802 Format Only</label>
[[input||type=text||name=mac||name_literal=mac||placeholder=54781A139264||required=required]]
</div>
<div class="columns small-3">
<label>Extension/Seat Number</label>
[[input||type=text||name=seat||name_literal=seat||placeholder=200]]
</div>
<div class="columns small-3">
<label>Display Name</label>
[[input||type=text||name=station||name_literal=station||placeholder=reception desk]]
</div>
One way could be to work with an array syntax as field name, for example: data[identifier][]. Otherwise you'll need to modify the name attribute after cloning:
var c = 0;
// each time you click on the button...
$(".clone").on('click',function(){
// generate a new clone of complete test div..
var klon = $( '#test').clone();
// append it to parent element (or after existing, as you like)
$('#test').parent().append(klon);
// increase global counter...
c++;
// inside clone find all inputs
// (if you other form elements, you must add them in selector)
klon.find('input').each(function() {
var $this = $(this),
name = $this.attr('name');
// update name attribute
$this.attr('name', name + '_' + (c));
});
});
See a fiddle here.
I still prefer the name / array solution, it is easier to handle server-side, because you can loop over the fields instead of asking for unkown amount of new fields.

jQuery events not firing

I have been trying to get this to work. Basically I have a search box that has a default string in it (i.e. Search) and it should go away when the user clicks on the input field.
Here is the code:
HTML:
<form method="get" action="index.php" id="search">
<span id="searchLogo"></span>
<input type='text' name='q' id='searchBox' value="Search <?php print $row[0]?> tweets!" autocomplete="off" />
</form>
Javascript/jQuery: (defaultString is a global variable that has the value of the textbox)
function clearDefault() {
var element = $('#searchBox');
if(element.attr('value') == defaultString) {
element.attr('value',"");
}
element.css('color','black');
}
$('#searchBox').focus(function() {
clearDefault();
});
Problem is here:
if(element.attr('value') == defaultString) {
element.attr('value',"");
}
Change it with:
if(element.val() == defaultString) {
element.val('value');
}
Update: Check it here:
http://jsfiddle.net/mr3T3/2/
The problem was that the event binding was not inside the $(document).ready() handler.
Fixed:
function clearDefault() {
var element = $('#searchBox');
if(element.val() == defaultString) {
element.val("");
}
element.css('color','black');
}
$(document).ready(function() {
$('#searchBox').focus(function() {
clearDefault();
});
});
It could be that event in fact is firing and your problem is in
if(element.attr('value') == defaultString) {
element.attr('value',"");
}
is "defaultString" properly defined?
put a simple alert() inside clearDefaults() and see if the event works.
i don't think clearDefault is reusable function, so don't create unnecessary function for small block of code. See the following code sample, i added a small improvement in your functionality.
<form method="get" action="index.php" id="search">
<span id="searchLogo"></span>
<input type='text' name='q' id='searchBox' default="Search tweets!" value="Search tweets!" autocomplete="off" />
</form>
$(document).ready(function() {
$("#searchBox").focus(function(e){
var $this = $(this);
if($this.val() == $this.attr('default')) $this.val('');
else if($this.val().length == 0 ) $this.val($this.attr('default'));
});
$("#searchBox").blur(function(e){
var $this = $(this);
if($this.val().length == 0 ) $this.val($this.attr('default'));
});
});
I added a default attribute to store default value and used it later on blur event.
See the example in jsFiddler

Categories

Resources