I have built the function below to search for text in jsTree.
If the search text is found, hightlight the node. If not found, alert user with "No node with the search string, try again" string.
What happens is when I put a search text that is not in jsTree, I get the alert. I search again with a valid text for the nodes but I still get the alert on the browser window.
Any ideas?
<script type="text/javascript">
function myFunction()
{
$(document).ready(function(){
var value=document.getElementById("search_field").value;
var searchResult;
var AlertsOn = false
$("#search_tree").click(function () {
searchResult=$("#tree").jstree("search",value);
if ($(searchResult).find('.jstree-search').length == 0)
{
AlertsOn = true;
}
else
{
AlertsOn = false;
}
if(AlertsOn == true){
alert($(searchResult).find('.jstree-search').length);
}
});
document.getElementById("search_field").value='';
});
}
</script>
html:
<fieldset id="search">
<input type="text" name="search_field" id="search_field" value="" />
<button id="search_tree" onclick="myFunction()"> Search</button>
</fieldset>
I can do this call in jquery to reload the page to re-initialize the alert box:
location.reload();
Related
The issue here is that I have designed a basic website which takes in a users input on a form, what I then intend to do is print that value out to the console.log. however, when I check the console under developer tools in Google Chrome, all I get printed out is []length: 0__proto__: Array(0)
and not the value the user has inputted.
<input type="text" name="username" value="testuser">
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<script>
function error() {
var error1 = [];
var list_of_values = [];
username_error = $('input[name="username"]').val();
if (!username_error){
error1.push('Fill in the username field.');
}
console.log(error1);
if (error1.length > 0){
for(let username_error of error1){
alert(username_error);
return false;
}
}
string = $('input[name="username"]').val('');
if(string.length <= 1){
for (let list_of_values of string){
string.push();
}
console.log(string);
return true;
}
}
error();
</script>
Suggestion, you can make it actually things easier with the following code.
the function below scans all input fields under fieldset element
$("fieldset *[name]").each....
the issue above is multiple alert, what if you have a lot of inputs, it would alert in every input, which wont be nice for the users :) instead you can do this
alert(error1.toString().replace(/,/g, "\n"));
to alert the lists of errors at once.
string = $('input[name="username"]').val('');
that is actually clearing your value.. so it wont give you anything in console.log().
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<fieldset>
<input type="text" name="name" value="" placeholder="name"/><br/><br/>
<input type="text" name="username" value="" placeholder="username"/><br/><br/>
<button onclick="error()">check</button>
</fieldset>
<script>
function error() {
var error1 = [];
var list_of_values = [];
$("fieldset *[name]").each(function(){
var inputItem = $(this);
if(inputItem.val()) {
return list_of_values.push(inputItem.val());
}
error1.push('Fill in the '+inputItem.attr('name')+' field!')
});
if(error1.length > 0) {
console.log(error1);
alert(error1.toString().replace(/,/g, "\n"));
}
if(list_of_values.length > 0) {
console.log(list_of_values);
}
}
</script>
Register the <input> to the input event. When the user types anything into the <input> the input event can trigger an event handler (a function, in the demo it's log()).
Demo
Details commented in demo
// Reference the input
var text = document.querySelector('[name=username]');
// Register the input to the input event
text.oninput = log;
/*
Whenever a user types into the input...
Reference the input as the element being typed into
if the typed element is an input...
log its value in the console.
*/
function log(event) {
var typed = event.target;
if (typed.tagName === 'INPUT') {
console.log(typed.value);
}
}
<input type="text" name="username" value="testuser">
I am working on a live search. I have made live searching using ajax where whatever alphabet I write in it, it displays the matching result to that alphabet or word. But the issue occurs when I click the cross button inside a search field it will clear the word inside input field but it is not refreshing my search and it is not showing data before a search but the result of the previous search.
I want my live search cross button functionality just like this -https://codepen.io/gastonbesada/pen/eqvJK
But this is in angular. I want the code in JavaScript.
And this is my code -
//let this page name is index.php
<div class="search">
<i class="fa fa-search" ></i>
<input type="text" id="searchterm" name="searchterm" placeholder="Search" >
</div>
<table id="result"></table>
//this is the script of index.php
<script>
$(document).ready(function(){
load_data();
function load_data(query)
{
$.ajax({
url:"search.php",
method:"post",
data:{query:query},
success:function(data)
{
$('#result').html(data);
}
});
}
$('#searchterm').keyup(function(){
var search = $(this).val();
if(search != '')
{
load_data(search);
}
else
{
load_data();
}
});
});
</script>
/* Search script for cross button inside input field*/
<script>
(function ($, undefined) {
$.fn.clearable = function () {
var $this = this;
$this.wrap('<div class="clear-holder" />');
var helper = $('<span title="Press Backspace" class="clear-helper">×</span>');
$this.parent().append(helper);
$this.parent().on('keyup', function() {
if($this.val()) {
helper.css('display', 'inline-block');
} else helper.hide();
});
helper.click(function(){
$this.val("");
helper.hide();
});
};
})(jQuery);
$("#searchterm").clearable();
</script>
just call your ajax with empty value again what you did in else part.
helper.click(function(){
$this.val("");
$this.trigger("keyup");
helper.hide();
});
I wants to check, if entered field's value is valid or not using onchange before submitting the page. I have written like below.It validates well.But how to activate 'NEXT' button when there is no error on input entries.
<div><input type="text" name="your_name" id="your_name" onchange = "validate_Name(this,1,4)" />
<span id="your_name-error" class="signup-error">*</span>
</div>
<div><input type="text" name="your_addr" id="your_addr" onchange = "validate_Name(this,1,4)" />
<span id="your_addr-error" class="signup-error">*</span>
</div>
<input class="btnAction" type="button" name="next" id="next" value="Next" style="display:none;">
<script type="text/javascript" src="../inc/validate_js.js"></script>
<script>
$(document).ready(function() {
$("#next").click(function() {
var output = validate(); //return true if no error
if (output) {
var current = $(".active"); //activating NEXT button
} else {
alert("Please correct the fields.");
}
});
}
function validate() {
//What should write here?I want to analyse the validate_js.js value here.
}
</script>
Inside validate_js.js
function validate_Name(inputVal, minLeng, maxLeng) {
if (inputVal.value.length > maxLeng) {
inputVal.style.background = "red";
inputVal.nextElementSibling.innerHTML = "<br>Max Characters:" + maxLeng;
} else if (!(tBox.value.match(letters))) {
inputVal.style.background = "red";
inputVal.nextElementSibling.innerHTML = "<br>Use only a-zA-Z0-9_ ";
} else {
inputVal.style.background = "white";
inputVal.nextElementSibling.innerHTML = "";
}
}
If by "activating" you want to make it visible, you can call $('#next').show().
However if you want to simulate a click on it, with jQuery you can simply call $('#next').click() or $('#next').trigger('click') as described here. Also, you might want to put everything in a form and programmatically submit the form when the input passes validation.
You could possibly trigger the change event for each field so it validates each one again.
eg.
function validate() {
$("#your_name").trigger('change');
$("#your_addr").trigger('change');
}
I have a project which I have to calculate the coordenates between two points. The first coordenates are calculated once the user enters in three text boxes the street, province and city.
How can I execute the code I have in PHP once the user fills out all three boxes and not before?
<form name="form" action="" method="post">
<input type="text" name="provincia" id="provincia">
<input type="text" name="municipio" id="municipio">
<input type="text" name="calle" id="calle">
<input type="submit" value="¡Buscar!"/>
</form>
This is the form the user has to fill in. Once the user writes in all three (without mattering the order) I have php code which Im not sure if it can execute once these boxes have values.
What should I have to use to accomplish this? Ajax? Jquery? Javascript?
Not really sure,
thanks.
are you looking for this?
$(document).ready(function () {
var flag = false;
$("input[type=text]").change(function () {
flag = true;
$("input[type=text]").each(function () {
if ($(this).val().trim() == "") {
flag = false;
}
});
if (flag) {
alert("all have values");
$("input[type=submit]").trigger("click");
}
alert(values);
});
});
edit
<form name="form" action="" method="post">
<input type="text" class="tobeChecked" name="provincia" id="provincia">
<input type="text" class="tobeChecked" name="municipio" id="municipio">
<input type="text" class="tobeChecked" name="calle" id="calle">
<input type="submit" value="¡Buscar!"/>
</form>
$(document).ready(function () {
var flag = false;
$(".tobeChecked").change(function () {
var values = "";
flag = true;
$(".tobeChecked").each(function () {
values += $(this).val().trim() + "+";
if ($(this).val().trim() == "") {
flag = false;
}
});
if (flag) {
alert("all have values");
$("input[type=submit]").trigger("click");
}
});
});
Create a function to validate the required field for those three text boxes and once all are filled with values execute your script:
$('#provincia,#municipio,#calle').blur(function(){
if($('#provincia').val() !="" && $('#municipio').val() !="" && $('#calle').val() !=""){
// Do your process here
}
});
You can use jquery validate plugin to validate these 3 input fields on the client side itself, In that way, the user cannot submit the form until he completely fills the input fields.
Give your Button an ID like:
<input type="submit" id="button" value="¡Buscar!"/>
Then you can do this in JQuery:
$("#button").click(function(){
//Get the value of the fields
var textfield1 = document.getElementById("provincia").value;
var textfield2 = document.getElementById("municipio").value;
var textfield3 = document.getElementById("calle").value;
//Check if Values are filled
if ( !textfield1.match(/\S/) || !textfield2.match(/\S/) || !textfield3.match(/\S/))
{
//execute your script
}
I hope it helps.
use jquery .change() function
$( "#provincia" ).change(function() {
//you can do something here
alert( "Handler for .change() called." );
});
I have three PHP pages. In first file, there are two divisions, of which, one division contains a list of hyperlinked URLs and second division loads the output of clicked hyperlinked URL. Below is the snippet for first file:
<script>
$(document).ready(function() {
$('a').each(function(){
$(this).on("click",function(e) {
console.log(e);
e.preventDefault();
$('#sidebar').load($(this).attr('href'));
});
});
</script>
<div id="content"> Sidebar <p> </p>
<div class="form">
<pre>
<a href=sample_form1.php><b>Psychotic Drug</b></a><p>
<a href=sample_form2.php><b>Antibiotic</b></a><p>
<a href=sample_form3.php><b>Pain killer</b></a><p>
<a href=sample_form4.php><b>Anti viral</b></a><p>
</pre>
</div>
In second file, I have form which is getting opened in first file's second division. Below is the code snippet for second file:
function validateForm()
{
var x=document.forms["drugForm"]["dname"].value;
var y=document.drugForm.drug;
//var y = new Array();
if (x==null || x=="")
{
alert("First name must be filled out");
return false;
}
else if (Boolean(x))
{
for(k=0;k<y.length;k++)
{
if(y[k].checked)
{
alert(" " + y[k].value);
return true;
}
}
alert("Check one checkbox at least");
return false;
}
}
</script>
<form name="drugForm" action="form1.php" onsubmit="return validateForm()" method="post">
Drug name: <input type="text" name="dname"></pre>
<pre>
<input type="checkbox" name="drug" value="ID">DRUG-ID <input type="checkbox" name="drug" value="Tree">Drug Tree</br>
<input type="checkbox" name="drug" value="Node">Node <input type="checkbox" name="drug" value="patent">Patent</br></br>
<input type="submit" value="Submit">
</pre>
</form>
I want to load this file in the first file's second division and that is happening as desired. But whenever I am trying to submit the input, form remains unresponsive. i.e. form entry is not being accepted and onclick function is not working. Please guide me in this regard how can I load multiple PHP/HTML files in one division.
I guess the inline js in your form isn't evaluated by jQuery's ajax function (for which $.load is just a shortcut).
You could try moving that section no the main file, which would read:
<script>
$(document).ready(function() {
$('a').each(function(){
$(this).on("click",function(e) {
console.log(e);
e.preventDefault();
$('#sidebar').load($(this).attr('href'));
});
$(document).on('submit','form[name=drugForm]',function() {
var x=document.forms["drugForm"]["dname"].value;
var y=document.drugForm.drug;
if (x==null || x=="") {
alert("First name must be filled out");
return false;
} else if (Boolean(x)) {
for(k=0;k<y.length;k++) {
if(y[k].checked) {
alert(" " + y[k].value);
return true;
}
}
alert("Check one checkbox at least");
return false;
});
});
</script>
Still, it seems to me this is an ugly way to deal with the whole structure. There's some heavy refactoring on its way.