Sid Sid - 3 months ago 13
CSS Question

jQuery display property not changing but other properties are

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?

Answer

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>