jQuery display property not changing but other properties are - javascript

I'm trying to make a text editable on clicking it. Below is the code I'm trying. When the title is clicked it shows an input box and button to save it.
<div class="block">
<div class="title">Title</div>
<div class="title-edit">
<input type="text" name="title" value="Title">
<button>Save</button>
</div>
</div>
I have changed other properties like color or changing the text of the elements and its working, but it is not applying the display property or .show()/.hide() function on the title or edit elements.
Below is my jQuery
$(function(){
$('.block').on('click', editTitle);
$('.title-edit button').on('click', saveTitle);
});
function saveTitle(){
var parent = $(this).closest('.block');
var title = $('.title', parent);
var edit = $('.title-edit', parent);
$(title).show();
$(edit).hide();
}
function editTitle(){
$('.title-edit', this).show();
$('.title', this).hide();
}
Here's the jsfiddle
https://jsfiddle.net/ywezpag7/
I've added
$(title).html('abcd');
to the end to show that other properties/functions are working, but just not the display.
For checking the html change on title element you will have to check the source through developer tools cause the title element is hidden.
Where am I going wrong?

Your problem is in the function saveTitle. The first line must stop the event propagation otherwise after this function the editTitle function is called.
The snippet:
$(function(){
$('.block').on('click', editTitle);
$('.title-edit button').on('click', saveTitle);
});
function saveTitle(e){
// this line
e.stopPropagation();
var parent = $(this).closest('.block');
var title = $('.title', parent);
var edit = $('.title-edit', parent);
title.show();
edit.hide();
title.text($('.title-edit input').val());
}
function editTitle(e){
$('.title-edit', this).show();
$('.title', this).hide();
}
.title-edit{
display:none
}
<script src="https://code.jquery.com/jquery-1.12.4.min.js"></script>
<div class="block">
<div class="title">Title</div>
<div class="title-edit">
<input type="text" name="title" value="Title">
<button>Save</button>
</div>
</div>

The issue as mentioned already is that your click events are fighting. In your code, the title-edit class is within the block, so when you click on the save button it triggers events for both clicks.
The easiest and, imho, cleanest way to resolve this is to switch your click event to be called on .title, and .title-edit button. You can also simplify the code beyond what you've got there.
$(function(){
$('.title').click(editTitle);
$('.title-edit button').click(saveTitle);
});
function saveTitle(){
$('.title').show();
$('.title-edit').hide();
$(title).html('abcd');
}
function editTitle(){
$('.title-edit').show();
$('.title').hide();
}
https://jsfiddle.net/ywezpag7/7/

I tried debug your code, and I had seen, that then you click to "Save" button, handled both functions, saveTitle() and editTitle(), and in that order. Therefore, the elements initially hidden, and then shown.

Related

Show hide/div based on drop down value at page load

I have the following code that I use to hide/show a div using a drop-down. If the Value of the drop-down is 1, I show the div, otherwise I hide it.
var pattern = jQuery('#pattern');
var select = pattern.value;
pattern.change(function () {
if ($(this).val() == '1') {
$('#hours').show();
}
else $('hours').hide();
});
The select drop down retrieves its value from the database using form model binding:
<div class="form-group">
<label for="pattern" class="col-sm-5 control-label">Pattern <span class="required">*</span></label>
<div class="col-sm-6">
{{Form::select('pattern',['0'=> 'Pattern 0','1'=> 'Pattern 1'],null,
['id'=>'pattern','class' => 'select-block-level chzn-select'])}}
</div>
</div>
This select drop-down then hides or shows the following div:
<div id="hours" style="border-radius:15px;border: dotted;" >
<p>Example text</p>
</div>
The problem:
The div won't be hidden if the pattern stored in the database is set to 0. I have to manually select "Pattern 0" from the drop down to change it. I know that is due to the .change() method. But how do I make it hide/show on page load?
Usually in such case I store the anonymous function reference as below:
var checkPattern = function () {
if ($('#pattern').val() == '1') {
$('#hours').show();
}
else $('#hours').hide();
}
It makes the code ready to use in more then one place.
Now your issue could be resolve in a more elegant way:
$(document).ready(function(){
// add event handler
$('#pattern').on('change', checkPattern);
// call to adjust div
checkPattern();
});
Well, if the element "should" be visible by default, you just then have to check condition to "hide it" (you don't have to SHOW an element that is already visible...) :
if(pattern.value != %WHATEVER%) { $('#hours').toggle(); }
Then, to switch display on event or condition or whatever :
pattern.change(function(evt){
$('#hours').toggle();
});
Not sure that your event will work. I'd try something like
$(document).on(..., function(evt){
//behaviour
});
http://api.jquery.com/toggle/
https://learn.jquery.com/events/handling-events/

How to use .hasClass with $(this)?

I have a header on my page, and block with boxes. That boxes represents my projects. When I click on one of them it is suppose to change my header background.
<div class="row">
<div class="job-one one-half column" onclick="headerProjBackground()">
<p>First</p>
</div>
<div class="job-two one-half column" onclick="headerProjBackground()">
<p>Second</p>
</div>
</div>
And my function:
function headerProjBackground(){
if($(this).hasClass('job-one')){
console.log('Hi!');
$('header').css('background-image': 'url(css/images/first-thing.png)');
}
if($(this).hasClass('job-one')){
console.log('Hello!');
$('header').css('background-image': 'url(css/images/second-thing.png)');
}
}
But it is not working. It can't understand my (this). There are no errors in the console. So this is logical mistake.
Onlcick attribute in Javascript by default Runs under Window, that means "this" object in the the function will always be window and as it doesn't have any class associated with it, so it will always give false in both if statement.
Refer below updated code snippet -
$('.jSelector').click(function(){
if($(this).hasClass('job-one')){
console.log('First Clicked!');
}
if($(this).hasClass('job-two')){
console.log('Second Clicked!');
}
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="row">
<div class="job-one one-half column jSelector">
<p>First</p>
</div>
<div class="job-two one-half column jSelector">
<p>Second</p>
</div>
</div>
Hope this helps!!
Outside of the onclick attribute, this is no longer defined. You can fix this in (at least) two ways.
Alt 1: Pass this as a parameter:
<div class="job-one one-half column" onclick="headerProjBackground(this)">
function headerProjBackground(clicked) {
//Replace this with clicked in the code of the function.
Alt 2: Do the event binding with jQuery instead of with HTML attributes:
<div class="job-one one-half column backgroundchanger">
$(".backgroundchanger").click(function() {
//Put the same code as for headerProjBackground() in your question.
//Here you can use the this keyword.
});
And some further thoughts: The way you have coded this is not very good if you want it compact (and clear). So lets try to improve it some! If you go with Alt 2 you could use a custom data- attribute to shorten the code:
<div class="one-half column" data-background="css/images/first-thing.png">
//If something that has the data-background attribute is clicked.
$('[data-background]').click(function() {
//Get the value from the data-background attribute, and use that as background image.
var background = $(this).attr('data-background');
$('header').css('background-image': 'url(' + background + ')');
});
Or, if you use Alt 1, you could just pass the desired background url as a parameter instead of this.
You can remove the onclick attribute on your divs and add the following, also the .css method has two parameters with comma between them.
<script type="text/javascript">
// once the dom is ready
$(document).ready(function() {
// check if any of the divs with column class is clicked
$('.column').click(function() {
// trigger the function and pass the (this) which is the object for the div clicked
headerProjBackground(this);
});
});
// element passed will be worked on in the function
function headerProjBackground(element){
if($(element).hasClass('job-one')){
console.log('Hi!');
$('header').css('background', '#000');
}
if($(element).hasClass('job-two')){
console.log('Hello!');
$('header').css('background', '#DDD');
}
}
</script>

Get a variable immediately after typing

I have this code
<span></span>
and this
<div> variable like a number </div>
and
<script>
$(document).ready(function(){
var x = $('div').html();
$('span').html(x)
});
</script>
I need that every time I change the div value, the span reflects the changes of the div
For example.
If I type 1 in the div, the span should immediately show me number 1
If I type 3283 in the div, the span should immediately show me number 3283
but with this code - I need to create
$("div").click(function(){
var x = $('div').html();
$('span').html(x)
});
I do not want to use .click(function) . in need this function run Automatically
after your answer
I use this code
http://jsfiddle.net/Danin_Na/uuo8yht1/3/
but doesn't work . whats the problem ?
This is very simple. If you add the contenteditable attribute to the div, you can use the keyup event:
var div = $('div'),
span = $('span');
span.html(div.html());
div.on('keyup', function() {
span.html(div.html());
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<span></span>
<div contenteditable="true"> variable like a number </div>
here is a demo with input:
html:
<span></span>
<input type="text" id="input01">
js:
$(document).ready(function(){
$( "#input01" ).on('keyup',function() {
var x = parseFloat($('#input01').val());
$('span').html(x)
});
});
How can you edit in div element on browser?
It have to be any input type then only you can edit or change value.
So for that on click of that div you have to show some input/textarea at that place and on change event of that input you can update the value of input in span.
<div id="main-div">
<input type="text" id="input-box" />
</div>
<script>
$(document).ready(function(){
$('#input-box').change(function(){
$('span').html($(this).text)
});
});
</script>
$("input[type=text]").change(function(){
var x = $('div').html();
$('span').text(x)
});
This can be use with textbox or textarea, For div user cannot enter text.
http://jsfiddle.net/uuo8yht1/
.change() will not work with a DIV-element. Since you did not specify how the DIV is updated I would recommend either setting a timer or using .keypress()
Example with timer:
$(function(){
var oldVal = "";
var divEl = $("div");
setInterval(function(){
var elTxt = divEl.text();
if (elTxt != oldVal) {
oldVal = elTxt;
$("span").text(elTxt);
}
}, 50);
});
You need a key listener, jquery provides a .keypress(), Examples are provided on keypress documentation.
I recommend to lookup the combination of .on() and .keyup() with some delay or throttle/debounce either via jquery or underscore.js library.
One of the reason or need for delay is to prevent too many event calls which will affect performance.
Here is an example of code in another question regarding throttle and keyup
Hope this helps.

Append a div outside of the input parent

Im fairly new to javascript and I just can't figure this out despite my attempt in researching. How do I track the change of a input within a div and trigger an append to an outside div? My code goes as follow:
Append h3 with "Pending" once ".image-value" input has a change in value
<!-- APPEND <h3> -->
<h3>Best Overall Costume<div class="pending">Pending</div></h3>
<div>
<div class="select-form">
<img src="images/vote.jpg" data-value="image_value">
<img src="images/vote.jpg" data-value="image_value2">
<img src="images/vote.jpg" data-value="image_value3">
<img src="images/vote.jpg" data-value="image_value4">
<img src="images/vote.jpg" data-value="image_value5">
<!-- Track the change of this input -->
<input type="hidden" class="image-value" name="selected_image" value="">
</div>
</div>
I tried this:
function changeStatus(statusValue) {
$("input",".select-form").val(statusValue).trigger("change");
}
$("input",".select-form").change(function(){
if (!$(this).val()){
$("<div class='pending'>Pending</div>").appendTo($("h3").prev($(this)));
}
});
But that didn't seem to work. Any ideas?
place an empty div where you want your new div and give it an id i.e(<div id='myDiv'><div>) and then append what you want like this.
$( "#myDiv" ).append( "<div class='pending'>Pending</div>" );
You can also check Append Explained
for more explanations.
Thanks.
I've done a couple things here... First, I'm not sure why you had it all in a named function. When you're using event listeners that often isn't necessary.
Then, I don't know what the val check was for, so I reversed it.
Finally, I'm using one(), which only runs once. This case seemed to call for that.
$('.select-form').one('change', 'input', function () {
if ( $(this).val() ) { alert('asdgf');
$("<div class='pending'>Pending</div>")
.appendTo($(this).parent().prev('h3'));
}
});
Fiddle
try this:
$("input",".select-form").on("change", function(){
var $this = $(this);
if (!$this.val()){
var elem = $('<h3>Best Overall Costume<div class="pending">Pending</div></h3>');
$this.parent().parent().before(elem);
}
});
you can also place a check, that if the pending div is already added, not to add it again.
Of course this solution assumes that there are no other nested divs between the target div(before which you want to append) and the input control

remove onclick when attached to children

I have the following code:
layoutOverlaysBldg = $("#layout-overlays-bldg")
layoutOverlaysBldg.on("click", "div", function(event) {
var floor;
console.log("floornum: " + this.dataset.floornum);
floor = parseInt(this.dataset.floornum);
...
$("#choose-floor").fadeOut();
$("#choose-apt").fadeIn();
});
later - based on data I'm getting back from the DB - I want to remove some of the .on("click", "div", ...) from only some of the divs. I already have the selector that is getting the right divs but I cannot figure out how to remove the click event. I have tried .off("click") after selecting the right div but it has no effect.
This issue here is because you are using a delegated event. You can add or remove the event for all child elements, but not individual ones given your div selector.
With that in mind the easiest way to do what you need is to add the event based on a class, then add and remove that class on the children as needed. Something like this:
layoutOverlaysBldg = $("#layout-overlays-bldg")
layoutOverlaysBldg.on("click", "div.clickable", function(event) {
// your code...
});
You can then enable/disable the event on the child div by adding or removing the .clickable class.
You can try like this :
Example :
<div id="test">
<div id="first">first</div>
<div id="second">second</div>
</div>
<div onclick="unbindSecondDiv();">UNBIND</div>
<script>
function unbindSecondDiv()
{
test = $("#second")
test.unbind("click");
alert('Selected Area Click is Unbind');
}
$(document).ready(function(){
//BIND SELECTED DIV CLICK EVENT
test = $("#test > div")
test.bind("click" , function(event) {
alert($(this).attr('id'));
});
});
</script>
In the above example , selected DIV elements click event is bind.
And after execute function unbindSecondDiv() , second DIV click event will be unbind.
Have a try , may helps you.

Categories

Resources