Toggle Button to change text, icon and show search bar - javascript

I do have a header with a navigation bar. The navigation includes a search button that each time is clicked should change the word from "Search" to "Close Search" and open the search bar initially not displayed below the navigation bar. I tried different ways with .html, .text but the text in the search button sometimes does work and others doesn't. I tried different approaches, but it is not consistent. Every time I click on the "Search" button, it should change the text and open and close the search bar, not just once. I tried using toggle() as well. I paste here below the code for button and search bar.
Also, the search button should display a search icon, defined by the class "btn-search-icon", which disappears once the searchbar closes and the button has the text "close search". The search bar below has a "search" field, submit button and a cancel button. The cancel button should remove the value in the search field. This step works but it reloads the page and as a consequence it closes the search bar, while it should stay open.
Any ideas? I appreciate any help.
HTML:
<button class="bg-btn btn-search btn-search-icon" id="searchBtnBar" type="submit" value="true">Search</button>
div class="container search-bar-container">
<form id="bgSearchBar">
<input type="search" name="searchfield" value="Search" class="searchField">
<button class="bgsearchbtn">Search <i class="fa-solid fa-arrow-right"></i></button>
<button class="bgcancelhbtn"></button>
</form>
</div>
JQuery:
$('#bgSearchBar').hide();
$("#searchBtnBar").click(function () {
$(this).fadeOut(function () {
$(this).text(($(this).text() == 'Search') ? 'Close Search' : 'Search').fadeIn();
})
$(this).toggleClass('btn-search-icon');
$('#bgSearchBar').fadeIn();
})
$(".bgcancelhbtn").on("click", function(event) {
$(".searchField").val("");
});

I tried to make minimal changes so it would work.
$('#bgSearchBar').hide();
$("#searchBtnBar").click(function() {
var flag = ($(this).text() == 'Search');
$(this).fadeOut(function() {
$(this).text(flag ? 'Close Search' : 'Search').fadeIn();
})
$(this).toggleClass('btn-search-icon');
if (flag) {
$('#bgSearchBar').fadeIn();
} else {
$('#bgSearchBar').fadeOut();
}
})
$(".bgcancelhbtn").on("click", function(event) {
$(".searchField").val("");
});
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.1.2/css/all.min.css" integrity="sha512-1sCRPdkRXhBV2PBLUdRb4tMg1w2YPf37qatUFeS7zlBy7jJI8Lf4VHwWfZZfpXtYSLy85pkm9GaYVYMfw5BC1A==" crossorigin="anonymous" referrerpolicy="no-referrer"/>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/2.2.4/jquery.min.js"></script>
<button class="bg-btn btn-search btn-search-icon" id="searchBtnBar">Search</button>
<div class="container search-bar-container">
<form id="bgSearchBar">
<input type="search" name="searchfield" value="Search" class="searchField">
<button class="bgsearchbtn">Search <i class="fa-solid fa-arrow-right"></i></button>
<button class="bgcancelhbtn" onclick="this.closest('form').reset(); return false">Cancel</button>
</form>
</div>

Related

For dynamically generated search input element, click on small "x" to clear fails to trigger using .on('search', function ()

I have a static and dynamically generated search input box. When I enter a value in the search box and click the "x" to clear it, I get a trigger for the static search box, but nothing happens with the dynamically generated one when I click on the "x". Sample code below:
<html>
<head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.6.0/jquery.min.js"></script>
</head>
<body>
<div id="search_group" style="">
<div class="input-group">
<input type="search" class="form-control" id="search_text"/>
</div>
</div>
<h5 id="add_search" style="cursor:pointer">Dynamically ad Search Box</h5>
<p id="append_here"></p>
<script type="text/javascript">
//this works on the static search box, but not on the dynamic search box
$('input[type=search]').on('search', function () {
console.log('X clicked');
});
//add search box dynamically
$( "#add_search" ).on( "click", function() {
var new_search_element = `<div id="search_group">
<div class="input-group">
<input type="search" class="form-control" id="search_text"/>
</div>
</div>`;
$("#append_here").empty().append(new_search_element);
});
</script
</body>
</html>
How can I get the dynamically generated search box to respond to a click on the "x"?
Your help is appreciated!
I think you should have to learn "Event Bubbling"
Easy to Paste this link
https://bokboot.net/read?id=62&key=fdfd681c-1807-4e93-9ca4-b0f68a6717b5
$('#search_group').on('search', function (e) {
if(e.target.id != "search_text") return;
console.log('X clicked');
$("#data").empty();
});

Bootstrap change button value

I'm having trouble changing a button value in bootstrap. I can change it using jQuery, but i'm changing it from a modal dialog. I looked elsewhere on SO but I couldn't find anything that seemed to match my specific issue?
Steps:
Click button. Change button text on main html form. Upon clicking the
button it changes the text, closes the modal, and then immediately
the text changes back to what it was originally. It should just change the text and stay that way, obviously.
$("#validate-rv-button").click(function () {
$("#review-history-validate").val("Review History");
});
HTML
<input id="review-history-validate" type="button" class="rvButtons btn btn-outline-warning btn-sm" data-toggle="modal" data-target="#review-history" value="Validate" />
Any help would be much appreciated.
Another way to do it with <button></button>
<button id="review-history-validate" type="button" class="rvButtons btn btn-outline-warning btn-sm" data-toggle="modal" data-target="#review-history" />Validate</button>
in jquery:
$("#validate-rv-button").click(function () {
$("#review-history-validate").text("Review History");
});
I believe you got the naming wrong.
This works:
$("#review-history-validate").click(function () {
document.getElementById("review-history-validate").value = "My value";
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input id="review-history-validate" type="button" class="rvButtons btn btn-outline-warning btn-sm" data-toggle="modal" data-target="#review-history" value="elo" />
Or jQuery only as your question:
$("#review-history-validate").click(function () {
$("#review-history-validate").val("My value");
});

Remove class from buttons on changing values in editable div for dynamically generated divs

I am creating an app using knockout and jquery. There are user generated contents which a user can edit and save. I have a save button which is disabled and gets enabled only when new character is added to the editable div.
Problem:
Save button gets activated for all divs. I want only the respective button to get enabled and remaining should stay in disabled state.
HTML:
<div data-bind="foreach: $root.goals">
<div class="ui padded segment mainCard brdR-S" data-bind="attr:{id:Title()}">
<div>
<div>
<div contenteditable="true" class="heading pdM-TB wordwrap" data-bind="attr:{href:'#'+Title()}, editableText: Title, event: { keyup: $root.ShowButtons }" id="goalTitle">
</div>
<div class="mgXl-T pdM-TB">
<button class="ui disabled tiny primary button" id="btnSave" data-bind="click: $root.putGoal">
<i class="refresh icon"></i>Save
</button>
</div>
</div>
</div>
</div>
Jquery
self.ShowButtons = function (data, e) {
$('.button').removeClass('disabled')
};

How to add <textarea> before button with jquery

I have a simple list of "News Articles" that I would like to be available for commentary. I've created an "Add Comment" button.
I want the button to create a <form> with a <textarea> immediately before the clicked button AND also create a "Cancel" button immediately after the clicked button. (I figured this out while posing this question)
The only thing that remains is that I would like the "Cancel" button to delete the newly created <textarea> and itself upon click. AND for extra credit, how do I prevent the "Add Comment" button from making more than one blank "textareas"?
$(document).ready(function(){
$(".AddComment").click(function () {
$("<form><textarea name='ResearchUpdate' placeholder='Enter your comment here' rows='3' cols='40' class='Commentary'></textarea> </form>").insertBefore(this);
$("<button class='CancelComment'>Cancel</button>").insertAfter(this);
});
$(".CancelComment").click(function (){
$(this).prev(".Commentary").remove();
$(this).remove();
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<!DOCTYPE html>
<html>
<head>
<title>News Entries</title>
</head>
<body>
<h2>Killer Rabbit On The Loose</h2>
<p>Date: 01/23/2015</p>
<p>Author: Bobert</p>
<p>Subject: Animals</p>
<p>Most Recent Comment: None Yet.</p>
<button class="AddComment">Add Comment</button>
<h2>Porsche Unveils Ultra Fast Minivan</h2>
<p>Date:02/14/2015</p>
<p>Author: Jimmy</p>
<p>Subject: Cars</p>
<p>Most Recent Comment:</p>
<p>This is genius on Porsche's behalf! I can drop off the kids at school, go grocery shopping and still have time to go racing with my buddies. All without worrying that my emissions aren't falsified and polluting the world. --SemiProRacer997</p>
<button class="AddComment">Add Comment</button>
<h2> Apple Releases iPhone Inifity</h2>
<p>Date:03/11/2015</p>
<p>Author: Frank</p>
<p>Subject: Technology</p>
<p>Most Recent Comment:</p>
<button class="AddComment">Add Comment</button>
</body>
</html>
<script type="text/javascript">
$('.AddComment').one('click',function(e){
e.preventDefault();
var bt=$(this);
var el=$('<textarea name="comment" />');
el.insertBefore(this);
bt.text('Send comment').on('click',function(e){
if (el.val().length==0){
alert("Please fill the comment before send.");
el.focus(); //Delete this row if you don't want user to focus on the textarea.
return false;
}
$.ajax({
type: 'POST',
data : el,
cache: false,
url: 'postUrl.php',
success: function(data){
bt.after($('<b>Comment sent</b>').hide().fadeIn());
bt.add(el).hide();
}
})
})
})
</script>
It is better to show and hide already existing items, than creating on the fly and inserting them.
Extra credit for not making Add Comment more than one textarea:
$(".AddComment").click(function () {
$("<form><textarea name='ResearchUpdate' placeholder='Enter your comment here' rows='3' cols='40' class='Commentary'></textarea> </form>").insertBefore(this);
$("<button class='CancelComment'>Cancel</button>").insertAfter(this);
// Remove the click event and disable the button.
$(this).off("click").prop("disabled", true);
});
My proposed solution:
Make sure you load the the comment box with every post with a class .comment-box and a style="display: none;" and use the following event handler.
$(".AddComment").click(function () {
$(this).prev(".comment-box").toggle();
});
Also, you can have the cancel button to have the following event handler:
$(".cancel").click(function () {
$(this).closest(".AddComment").hide();
});
The best solution is to wrap every post items in a container div with a css class which we can use for jQuery selection later.
<div class="postItem">
<h2>Killer Rabbit On The Loose</h2>
<p>Date: 01/23/2015</p>
<p>Author: Bobert</p>
<button class="AddComment">Add Comment</button>
</div>
<div class="postItem">
<h2>Second post</h2>
<p>Date: 01/23/2015</p>
<p>Author: Shyju</p>
<button class="AddComment">Add Comment</button>
</div>
And in your cancel button click event, get the container div, find the form and the cancel button and remove it,
$(document).on("click",".CancelComment",function (e){
var _this = $(this);
_this.closest(".postItem").find("form").remove();
_this.remove();
});
Working sample here
You need to use jQuery on method to bind the click event on the cancel button as they are dynamically created by your code and injected to the DOM.
I would have the form there already but have it hidden so that when you click the button it appears. You can then disable the button using $('#buttonId').prop('disabled', true);
This will prevent any further clicks although the click wouldn't matter this way anyway as you only have one form to show so it wouldn't pop up any more.
Clicking the cancel button should fire a function that removes the content of the textarea in question, hides the form/textarea and re-enables the comment button
show_comment :
function show_comment(){<br>
$('#formId').show();<br>
$('#cancelButton').show();<br>
$('#commentButton').prop('disabled', true)<br>
}
remove_comment:
function remove_comment(){<br>
$('#textareaId').html('');<br>
$('#commentButton').prop('disabled', false);<br>
$('#cancelButton').hide();
}
Issues in your code.
You are adding click function for cancel button that does not exist on page load. You will have to add click after you add cancel button
You are doing prev() on cancel button which is wrong. The prev sibling of cancel button is add comment button and not text area.
Please see if following code fixes your issue.
I am also disabling add button once comment text area is added so that you dont add more text areas
$(document).ready(function(){
$(".AddComment").click(function () {
var $addCommentBtn = $(this),
$commentTextArea;
$addCommentBtn.prop( "disabled", true );
$commentTextArea = $("<form><textarea name='ResearchUpdate' placeholder='Enter your comment here' rows='3' cols='40' class='Commentary'></textarea> </form>").insertBefore(this);
$("<button class='CancelComment'>Cancel</button>").insertAfter(this).click(function (){
$commentTextArea.remove();
$(this).remove();
$addCommentBtn.prop( "disabled", false );
});
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<!DOCTYPE html>
<html>
<head>
<title>News Entries</title>
</head>
<body>
<h2>Killer Rabbit On The Loose</h2>
<p>Date: 01/23/2015</p>
<p>Author: Bobert</p>
<p>Subject: Animals</p>
<p>Most Recent Comment: None Yet.</p>
<button class="AddComment">Add Comment</button>
<h2>Porsche Unveils Ultra Fast Minivan</h2>
<p>Date:02/14/2015</p>
<p>Author: Jimmy</p>
<p>Subject: Cars</p>
<p>Most Recent Comment:</p>
<p>This is genius on Porsche's behalf! I can drop off the kids at school, go grocery shopping and still have time to go racing with my buddies. All without worrying that my emissions aren't falsified and polluting the world. --SemiProRacer997</p>
<button class="AddComment">Add Comment</button>
<h2> Apple Releases iPhone Inifity</h2>
<p>Date:03/11/2015</p>
<p>Author: Frank</p>
<p>Subject: Technology</p>
<p>Most Recent Comment:</p>
<button class="AddComment">Add Comment</button>
</body>
</html>

Hiding/showing div by selecting dropdown and button click

i want to select a value from my dropdown, and then, when i click a button, it hides certain div and show another div. I'm baffled on how to achieved this. so i have two div.
<div id="div1"> some content </div>
<div id="div2"> some content </div>
#Html.DropDownListFor(model => model.Reference, ViewBag.ISharedUI as SelectList, "-- REFERENCE TYPE -- SHOW ALL", new { #id = "testID" })
and here is my button.
<input type="submit" value="Filter" name="Command" class="btn btn-default" onclick="abc()" />
and this is my function. I try to do it,
function abc() {
if ('#testID' != 1) {
$('#div1').show();
$('#div2').hide();
} else if (testID != 2) {
$('#div1').show();
$('#div2').hide();
} else {
$('#div1').hide();
$('#div2').hide();
}
}
I hope my question is clear.
I am unsure with what you want to do with the value from the dropdown input, but it is not too relevant to affecting the state of the divs if you are only interacting with the button to affect the divs.
In terms just hiding the div, you can apply a class "hidden" that hides the element or not with CSS.
Then you can toggle the div and whether or not it appears by clicking on the button with jQuery by adding and removing that hidden class with the toggleClass.
Let me know if you have any more questions.
$(document).ready(function() {
$(".btn").on("click", function() {
$("#div1").toggleClass("hidden");
$("#div2").toggleClass("hidden");
})
})
.hidden {
display: none;
}
<div id="div1"> some content </div>
<div id="div2" class="hidden"> some content </div>
<input type="submit" value="Filter" name="Command" class="btn btn-default" onclick="abc()" />

Categories