[javascript] Set value of textbox using JQuery

My Jade template -

input#main_search.span2(
    style = 'height: 26px; width: 800px;' ,
    type = 'text',
    readonly='true',
    name='searchBar',
    value='test'
)

JS file -

$('#searchBar').val('hi')
console.log('sup')

Console output -

sup

But searchBar value stats at test. What am I doing wrong?

This question is related to javascript jquery pug

The answer is


You are logging sup directly which is a string

console.log('sup')

Also you are using the wrong id

The template says #main_search but you are using #searchBar

I suppose you are trying this out

$(function() {
   var sup = $('#main_search').val('hi')
   console.log(sup);  // sup is a variable here
});

Make sure you have the right selector, and then wait until the page is ready and that the element exists until you run the function.

$(function(){
    $('#searchBar').val('hi')
});

As Derek points out, the ID is wrong as well.

Change to $('#main_search')


1) you are calling it wrong way try:

$(input[name="searchBar"]).val('hi')

2) if it doesn't work call your .js file at the end of the page or trigger your function on document.ready event

$(document).ready(function() {
  $(input[name="searchBar"]).val('hi');
});

$(document).ready(function() {
 $('#main_search').val('hi');
});

You're targeting the wrong item with that jQuery selector. The name of your search bar is searchBar, not the id. What you want to use is $('#main_search').val('hi').


Examples related to javascript

need to add a class to an element How to make a variable accessible outside a function? Hide Signs that Meteor.js was Used How to create a showdown.js markdown extension Please help me convert this script to a simple image slider Highlight Anchor Links when user manually scrolls? Summing radio input values How to execute an action before close metro app WinJS javascript, for loop defines a dynamic variable name Getting all files in directory with ajax

Examples related to jquery

How to make a variable accessible outside a function? Jquery assiging class to th in a table Please help me convert this script to a simple image slider Highlight Anchor Links when user manually scrolls? Getting all files in directory with ajax Bootstrap 4 multiselect dropdown Cross-Origin Read Blocking (CORB) bootstrap 4 file input doesn't show the file name Jquery AJAX: No 'Access-Control-Allow-Origin' header is present on the requested resource how to remove json object key and value.?

Examples related to pug

Angular 4: InvalidPipeArgument: '[object Object]' for pipe 'AsyncPipe' Node - how to run app.js? CSS how to make scrollable list Client on Node.js: Uncaught ReferenceError: require is not defined Change value of input placeholder via model? Set value of textbox using JQuery Change the "No file chosen": Error: Failed to lookup view in Express Loop in Jade (currently known as "Pug") template engine How to pass variable from jade template file to a script file?