Hide tables or forms in javascript - javascript

I would like to hide a element of HTML when I click in other element.
I have a menu with a submenu that has two options. One option shows a table and the other a form. When I click on the first option, the table appears. If after I click on the second option, the previous table and the form appear.
The menu is:
In action I get a table and in another action I get a form.
The code in HTML is:
<div class="collapse navbar-collapse" id="navbarNavDropdown">
<ul class="navbar-nav">
<li class="nav-item dropdown">
<a class="nav-link dropdown-toggle" href="#" id="navbarDropdownMenuLink" data-toggle="dropdown" aria-haspopup="true" aria-expanded="false">
Dropdown link
</a>
<div class="dropdown-menu" aria-labelledby="navbarDropdownMenuLink">
<a class="dropdown-item" href="#" onclick="origin()">Action</a>
<a class="dropdown-item" href="#" onclick="formOrigin()">Another action</a>
</div>
<div>
<table class="table"></table>
</div>
<div>
<form>
<div class="form-group">
<label for="name">Name</label>
<input type="text" class="form-control" id="name" placeholder="Enter name">
</div>
<div class="form-group">
<label for="city">City</label>
<input type="text" class="form-control" id="city" placeholder="city">
</div>
<div class="form-group form-check">
<input type="checkbox" class="form-check-input" id="add">
<label class="form-check-label" for="add">Check</label>
</div>
<button type="submit" class="btn btn-primary">Submit</button>
</form>
</div>
The code in Javascript is:
function origin() {
var url = "http://localhost:8000/api/v1/origin";
petition.onreadystatechange = ResponseOrigin;
petition.open("GET", url, true);
petition.send();
}
function ResponseOrigin(){
var response;
text="<tr><th>Identifier</th><th>Name</th><th>Numero</th><th>City</th></tr>";
if (petition.readyState == 4)
if (petition.status == 200) {
responser = petition.responseText;
var responseC = response.split("<");
var responseV = responseC[0];
var data = JSON.parse(responseV);
for (var i = 0; i < data.length; i++) {
text += "<tr id =" + data[i].id + "><td>" + data[i].id + "</td><td id='name'>" + data[i].name + "</td><td>" +
data[i].city + "</td>
document.getElementById('table').innerHTML = text;
document.formOrigin.style.display="none";
}
else alert("Problem with URL");
}
function formOrigin() {
var url = "http://localhost:8000/api/v1/origin";
petition.onreadystatechange = responseAddOrigin;
petition.open("POST", url, true);
petition.send(JSON.stringify({name: document.formOrigin.name.value,
city: document.formOrigin.city.value}));
}
function responseAddOrigen(){
var response;
if (petition.readyState == 4)
if (petition.status == 200) {
response = petition.responseText;
alert ("data recorded correctly");
}
else
alert("Problem with URL");
}

Since you're using bootstrap, you can try this:
$('yourTriggerElement').click(function(){
$('yourTargetElement').addClass('d-none');
});
This add bootstrap class 'd-none' to your target element, which is the same as display none. You can add some conditionals if you want to show the element again with the same trigger. Change 'yourTriggerElement' and 'yourTargetElement' with your real id's or classes.

Related

Button click function not working in jQuery

So I'm developing a website for a medical clinic and they asked me to add a button beneath every doctor to make an appointment.
this is what i have for the doctors section
for (var i = 0; i < 3; i++) {
$('#get_medicos').append(
'<div class="col-md-3 dummy">' +
'<div class="text-box">' +
'<img src="assets/images/corpo-clinico/' + medico[i].ficheiro + '" alt="" class="img-responsive"/>' +
'<div class="clearfix"></div>' +
'<div class="text-box white padding-3">' +
'<h5 class="less-mar1 text-blue">' + medico[i].nome +'</h5>' +
'<p>' + medico[i].especialidade + '</p>' +
'<a id="marcar" type="button" class="btn btn-primary">Marcar consulta</a>' +
'</div>' +
'</div>' +
'</div>'
);
}
The then code for the click function (that doesn't work):
$('#marcar').click(function() {
var offset = $('#marcacao').offset();
$('html, body').animate({
scrollTop: offset.top-100,
scrollLeft: offset.left
}, 1000);
$('#marcacao-consulta').find('#especialidade-marcacao option[id="default"]').text(medico[i].especialidade);
$('#marcacao-consulta').find('#corpo-clinico option[id="default"]').text(medico[i].nome);
console.log('test');
});
This is all inside a $(document).ready(function() {}); and what should do is when i click that button beneath the doctor, should go up to the form and fill the doctor's name and specialty... but it seems it's not working for some reason... this is a copy of other click functions in the code, but they seem to work fine.
HTML form:
<div id="marcacao-consulta" data-target="#marcacao-consulta">
<div class="row">
<div class="col-md-6 col-lg-6 col-sm-12">
<div class="section">
<label class="field select prepend-icon">
<select id="especialidade-marcacao" class="gui-input">
<option id="especialiade-default" value="default">Escolha a especialidade</option>
<?
$query = $dbHandle->prepare("
SELECT `especialidade`
FROM `especialidade`
ORDER BY `especialidade` ASC
");
$query->execute();
if ($query->rowCount() > 0) {
while ($row = $query->fetch(PDO::FETCH_ASSOC)) { ?>
<option value="<?=$row["especialidade"]; ?>"><?=$row["especialidade"]; ?></option>
<? }
} else { ?>
<option value="">Nenhum resultado</option>
<? }
?>
</select>
<span class="field-icon"><i class="fas fa-heartbeat"></i></span>
</label>
</div>
</div>
<div class="col-md-6 col-lg-6 col-sm-12">
<div class="section">
<label class="field select prepend-icon">
<select id="corpo-clinico-marcacao" class="gui-input">
<option id="corpo-clinico-default" value="default">Escolha o médico</option>
<?
$query = $dbHandle->prepare("
SELECT `nome`
FROM `medico`
ORDER BY `nome` ASC
");
$query->execute();
if ($query->rowCount() > 0) {
while ($row = $query->fetch(PDO::FETCH_ASSOC)) { ?>
<option value="<?=$row["nome"]; ?>"><?=$row["nome"]; ?></option>
<? }
} else { ?>
<option value="">Nenhum resultado</option>
<? }
?>
</select>
<span class="field-icon"><i class="fas fa-user-md"></i></span>
</label>
</div>
</div>
<div class="col-md-12 col-lg-12 col-sm-12">
<div class="section">
<label class="field prepend-icon">
<input id="nome" class="gui-input" type="text" placeholder="Nome Completo">
<span class="field-icon"><i class="fas fa-user"></i></span>
</label>
</div>
<div class="section">
<label class="field prepend-icon">
<input id="email" class="gui-input" type="text" placeholder="Endereço de correio eletrónico">
<span class="field-icon"><i class="fas fa-envelope"></i></span>
</label>
</div>
<div class="section">
<label class="field prepend-icon">
<input id="telefone" class="gui-input" type="text" placeholder="Telefone/Télemovel">
<span class="field-icon"><i class="fas fa-phone-square"></i></span>
</label>
</div>
<div class="section">
<label class="field prepend-icon">
<input id="tipo" class="gui-input" type="text" value="consulta" disabled>
</label>
</div>
</div>
</div>
</div>
You have to add the element and register the event for the element. Here is the fiddle which works for you
https://jsfiddle.net/0q3kpyfv/
Your sample HTML
<div id="get_medicos">
</div>
Sample jquery code
Notice I have added the data-val attribute to the added anchor tag which will help you to get the information and perform the logic based on which button is clicked. you can pass dynamic data to data-val attribute and use it in click event.
$(document).ready(function() {
var sampleString = "";
var medico = [{'especialidade':'speciality 0','nome':'Doctor 0'},{'especialidade':'speciality 1','nome':'Doctor 1'},{'especialidade':'speciality 2','nome':'Doctor 2'}]
for (var i = 0; i < 3; i++) {
var doctorData = medico[i];
$('#get_medicos').append(
'<div class="col-md-3 dummy">' +
'<div class="text-box">' +
'<img src="assets/images/corpo-clinico/' + medico[i].especialidade + '" alt="" class="img-responsive"/>' +
'<div class="clearfix"></div>' +
'<div class="text-box white padding-3">' +
'<h5 class="less-mar1 text-blue">' + medico[i].nome +'</h5>' +
'<p>' + medico[i].especialidade + '</p>' +
'<a id="marcar" data-doctor-especialiadade="'+medico[i].especialidade+'" data-doctor-nome="'+medico[i].nome+'" type="button" class="btn btn-primary">Marcar consulta'+i+'</a>' +
'</div>' +
'</div>' +
'</div>'
);
};
$('#get_medicos').on('click','a',function(event){
var elementClicked = event.target;
var doctorEspecialiadade = $(elementClicked).data('doctor-especialiadade');
var doctorName = $(elementClicked).data('doctor-nome');
$('#marcacao-consulta').find('#especialidade-marcacao option[id="default"]').text(doctorEspecialiadade);
$('#marcacao-consulta').find('#corpo-clinico option[id="default"]').text(doctorName);
})
});
if you create the button after your event, you could have problem so, use the delegate version of click:
$('div').on('click', 'a', (function()....
and better put an id on the ancestor div:
'<div class="text-box white padding-3" id="mydiv"'
:
$('#mydiv').on('click', 'a', (function()....
another thing, with the loop you will have same id more time in your html??its no good.
so you'll have to rebuild your program logic...and bind the event with the right button (use a common class) it will be better than an id
If you bind the event to the parent element, and filter by the children, you can listen to any new elements that are added, doesn't matter how many.
<div class="container"></div>
<button class="js-add-new">Add new</button>
const $addNew = $('.js-add-new')
const $container = $('.container')
let count = 0
$addNew.on("click", () => {
count += 1
$container.append(`
<div>
<button>log me ${count}</button>
</div>
`)
})
$container.on("click", "button", (event) => {
console.log(event.currentTarget)
})
A working example: https://codepen.io/alexmccabe/pen/jOrXZxj?editors=1111
The button click is working. Here is a fiddle showing it does:
https://jsfiddle.net/bradberkobien/qL4m10y6/3/
There must be an issue with the code that comes before the console.log("test") line within the click. I would use the debugger to help you with that.

appendChild + createElement is not working

The following block of code is not working.
instead of creating a list element with the text thats coming from the input, it just creates a text and appends it without creating a list element.
Can someone see where my mistake is?
var button = document.querySelector('#btn');
button.addEventListener('click', handleClick);
function handleClick(e) {
e.preventDefault();
var name=document.querySelectorAll('#item');
for (let i=0; i<name.length; i++) {
var x=name[i].value;
var item= document.createElement('li')
item.className="list-group-item";
var text= document.createTextNode(x);
var addList=item.appendChild(text);
var ul=document.getElementById('items').appendChild(addList);
console.log(document.getElementById('main').childNodes)
name[i].value='';
}
}
<div class="container">
<div id="main" class="card card-body">
<h2 class="title ">Create Contact
</h2>
<form id="addForm" class=" mb-3">
<input type="text" class="form-control mr-2 my-3" id="item" placeholder="First Name" required>
<input type="text" class="form-control mr-2 my-3" id="item" placeholder="Last Name" required>
<h6 id='warning' style="display:none">All fields are required.</h6>
<button id="btn" class="btn btn-dark">Create</button>
</form>
<h2 class="title">Items</h2>
<ul id="items" class="list-group">
<li class="list-group-item">x</li>
<li class="list-group-item" >y</li>
<li class="list-group-item" >z</li>
<li class="list-group-item" >g</li>
</ul>
</div>
</div>
var name=document.querySelectorAll('#item');
.querySelectorAll() is for getting more than one element.
# means id.
ID's must be unique within a document.
A button's default type is submit, which you don't want here. A
regular button is what you need.
See additional HTML, CSS, and JavaScript comments inline below:
// Get references to the elements you'll need just once:
let warning = document.getElementById("warning");
let fName = document.getElementById("fName");
let lName = document.getElementById('lName');
let list = document.getElementById("items");
// Set up event handler
document.getElementById("btn").addEventListener('click', handleClick);
function handleClick(){
// Check to see if required fields have data
if(fName.value == "" || lName.value == ""){
warning.classList.remove("hidden"); // Invalid! Show message
return; // Exit function
} else {
warning.classList.add("hidden"); // Valid! Hide message
}
// There's only two elements to worry about and each has a unique id
// so just do the work on each. A loop is overkill here.
// First name
var li= document.createElement('li')
li.className="list-group-item";
li.textContent = fName.value; // No need for a text node. Just set the text content
items.appendChild(li);
fName.value = "";
// Last Name
li= document.createElement('li')
li.className="list-group-item";
li.textContent = lName.value;
items.appendChild(li);
lName.value = "";
//console.log(document.getElementById('main').innerHTML)
}
/* CSS does all the layout and styling */
#warning { font-weight:bold; color:red; }
.hidden { display:none; }
<div class="container">
<div id="main" class="card card-body">
<h2 class="title ">Create Contact
</h2>
<form id="addForm" class=" mb-3">
<input type="text" class="form-control mr-2 my-3" id="fName" placeholder="First Name" required>
<input type="text" class="form-control mr-2 my-3" id="lName" placeholder="Last Name" required>
<!-- You need a regular button here. Not the default type, which is a submit. -->
<button type="button" id="btn" class="btn btn-dark">Create</button>
<!-- Heading elements (h1...h6) are to create sections of a document. You can't
have section 6 unless you've already had sections 1 - 5. Don't use heading
tags because of the way they make the text look. Style is CSS's job. -->
<div id='warning' class="hidden">All fields are required.</div>
</form>
<h2 class="title">Items</h2>
<ul id="items" class="list-group">
<li class="list-group-item">x</li>
<li class="list-group-item" >y</li>
<li class="list-group-item" >z</li>
<li class="list-group-item" >g</li>
</ul>
</div>
</div>

Manipulating element by ID

I'm creating a plugin for Input Files, I created everything but without having in mind the possibility of having multiple inputs on screen, then it was necessary instead to manipulate the element from the element ID. This is so that actions in one input do not affect all other inputs on the screen.
Below is the code so far, I could not make it work when informed by the element ID.
function bs_input_file() {
// TODO: add function to hide remove button when file not informed
const inputElement = $(".input-file").find('input');
const inputId = inputElement.map(function (index, dom) {
return dom.id
});
buttonInspec(inputId);
function buttonInspec(id) {
$("#" + id).find("button.btn-reset").addClass("hidden");
var element = $("#" + id).find('input');
element.on("change input propertychange", function() {
console.log("changed!")
if (element.val() != "") {
$("#" + id).find("button.btn-reset").removeClass("hidden");
}
});
}
// Necessary to put ID below also
$(".input-file").before(
function() {
if (!$(this).prev().hasClass('input-ghost')) {
var element = $("<input type='file' class='input-ghost' style='visibility:hidden; height:0'>");
element.attr("name", $(this).attr("name"));
element.change(function() {
element.next(element).find('input').val((element.val()).split('\\').pop());
});
$(this).find("button.btn-choose").click(function() {
element.click();
});
$(this).find("button.btn-reset").click(function() {
element.val(null);
$(this).parents(".input-file").find('input').val('');
});
$(this).find('input').css("cursor", "pointer");
$(this).find('input').mousedown(function() {
$(this).parents('.input-file').prev().click();
return false;
});
return element;
}
}
);
}
bs_input_file();
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/js/bootstrap.min.js"></script>
<link href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css" rel="stylesheet"/>
<div class="container">
<div class="col-md-8 col-md-offset-2">
<h3>Example</h3>
<form method="POST" action="#" enctype="multipart/form-data">
<!-- COMPONENT START -->
<div class="form-group">
<div class="input-group input-file" name="Fichier1">
<input id="fileInput0" type="text" class="form-control" placeholder='Select file...' />
<span class="input-group-btn">
<button class="btn btn-secondary btn-reset" type="button"><em class="glyphicon glyphicon-trash"></em></button>
<button class="btn btn-default btn-choose " type="button"><em class="glyphicon glyphicon-folder-open"></em> Search...</button>
</span>
</div>
</div>
<div class="form-group">
<div class="input-group input-file" name="Fichier2">
<input id="fileInput1" type="text" class="form-control" placeholder='Select file...' />
<span class="input-group-btn">
<button class="btn btn-secondary btn-reset" type="button"><em class="glyphicon glyphicon-trash"></em></button>
<button class="btn btn-default btn-choose " type="button"><em class="glyphicon glyphicon-folder-open"></em> Search...</button>
</span>
</div>
</div>
<!-- COMPONENT END -->
</form>
</div>
</div>

How to search result when select drop down using jquery?

<script>
$(document).ready(function(){
$("#find_jobs").click(function(){
$("#job").css("display","block");
$("#freelancer").css("display","none");
});
$("#find_freelancer").click(function(){
$("#job").css("display","none");
$("#freelancer").css("display","block");
});
$(".submitss").click(function(){
job_id = $(".job_search").attr('id');
job_val = $(".job_search").val();
alert(job_id);
alert(job_val);
});
});
</script>
<form class="form-horizontal" role="form" method="post" id="myform">
<div class="input-group" id="header-search">
<div class="input-group-btn">
<div class="btn-group" role="group">
<i class="fa fa-search"></i>
<div class="dropdown dropdown-lg">
<button type="button" class="btn btn-default dropdown-toggle" data-toggle="dropdown" aria-expanded="false" style="margin-top: 10px;"><span class="caret"></span></button>
<div class="dropdown-menu dropdown-menu-left" role="menu">
<div class="form-group">
<ul>
<li>Find Jobs</li>
<li>Find Freelancers</li>
</ul>
</div>
</div>
</div>
</div>
</div>
<input type="text" id="job" class="form-control job_search" placeholder="Search Job" name="job_search" style="display:block;"/>
<input type="text" id="freelancer" class="form-control freelancer_search" placeholder="Search Freelancer" name="freelancer_search" style="display:none;"/>
</div>
</form>
In this code, I have a search box form with list ul Now, What am I doing here when I select find_job then search job input field active and If I selected find_freelancer then freelancer input field active. Now, What I required When I click on class="submitss" or press enter key then it shows job_id and job_val but if I select then it shows freelancer_id and freelancer_val.
So, How can I do this? Please help me.
Thank You
If I understood you correctly, this should do the job. Basically if input#job is visible show job, else show freelancer. I don't really see the need to use two different input fields, but ok.
function submit() {
if ($("#job").css("display") === "block") {
job_id = $(".job_search").attr('id');
job_val = $(".job_search").val();
} else {
job_id = $(".freelancer_search").attr('id');
job_val = $(".freelancer_search").val();
}
alert(job_id);
alert(job_val);
}
$(document).ready(function(){
$(window).keydown(function(event) {
if (event.keyCode == 13) { // enter key
submit();
event.preventDefault();
return false;
}
});
$("#find_job").click(function () { // find_job not find_jobs
$("#job").css("display", "block");
$("#freelancer").css("display", "none");
});
$("#find_freelancer").click(function() {
$("#job").css("display", "none");
$("#freelancer").css("display", "block");
});
$(".submitss").click(submit);
});
Also
<a href="javascript:void();" class="submitss" id="submitss">
should be
<a href="javascript:void(0);" class="submitss" id="submitss">
or you get
Uncaught SyntaxError: Unexpected token )

How to search dropdown with input on PHP

hope all be will. I face to like this problem anyone can help me.
I get the value of dropdown and I put it to input, but I am unable to search it.
I used from jQuery to get the value from bootstrap dropdown to give for input.
<!-- HTML Code With Form -->
<!-- Basic dropdown -->
<form method="post" enctype="multipart/form-data" action="team.php"
class="form-inline active-purple-3 active-purple-4" style="width:400px;
margin-top:-50px; margin-left:125px; ">
<button id="sb" class="btn btn-primary dropdown-toggle mr-4" type="button"
data-toggle="dropdown" aria-haspopup="true" aria-expanded="false"
style="margin-top:20px; margin-left:-140px;">Search By</button>
<div class="dropdown-menu" id="dm" style="margin-left:89px; margin-
top:-963px;">
<a class="dropdown-item" id="dl" href="#" value="ID">BY ID</a>
<a class="dropdown-item" id="dl" href="#" value="Name">Name</a>
<a class="dropdown-item" id="dl" href="#" value="Positon">Position</a>
</div>
<input type='hidden' name='thenumbers'>
<!-- Basic dropdown -->
<!-- Search form -->
<i class="fa fa-search" aria-hidden="true" style="margin-top:15px;"></i>
<input name="txtSearch" class="form-control form-control-sm ml-3 w-75"
id="in" type="text" placeholder="Search" style=" margin-top:15px; border-
radius:5px 5px 5px 5px;" aria-label="Search">
<button type="Submit" name="searchrec" class="btn btn-primary"
style="margin-left:365px; margin-top:-55px;">Search</button>
</form>
<!-- jQuery Code -->
<script>
$(document).ready(function(){
$('#dm a').on('click', function(){
$('#sb').text($(this).text());
});
});
</script>
<script>
$(function(){
//Listen for a click on any of the dropdown items
$("#dm a").click(function(){
//Get the value
var value = $(this).text();
//Put the retrieved value into the hidden input
$("input[name='thenumbers']").val(value);
});
});
</script>
<!-- jQuery Code End -->
<!-- PHP Code -->
<?php
include "Config.php";
if(isset($_POST['searchrec']))
{
$txtSearch=$_POST['txtSearch'];
$column=$_POST['thenumbers'];
if($column == "BY ID")
{
$query1="SELECT * FROM ourteam WHERE id LIKE '%$txtSearch%'";
$result1=mysqli_query($db,$query1);
$count=mysqli_num_rows($result1);
if($count == 0)
{
}else{
while($rowr=mysqli_fetch_array($result1))
{
$id=$rowr['id'];
$name=$rowr['name'];
echo "<script>alert($name);</script>";
}
}
This PHP code is just for ID and I used elesif statement also for other entities.
First, get the values not the text:
//Get the value
var value = $(this).attr('value'); // instead of text
Then, map it on the server side
$allowed_columns = ['id', 'name', 'position'];
$column = $_POST['thenumbers'];
$txtSearch = $_POST['txtSearch'];
// Check the field name
if (!in_array($column, $allowed_columns)) {
// Throw some exception, or do whatever you want
}
// Sanitize the value
$txtSearch = mysqli_real_escape_string($txtSearch);
$query1="SELECT * FROM ourteam WHERE `$column` LIKE '%$txtSearch%'";
// ...

Categories

Resources