Uncaught TypeError: Cannot set property 'value

2020-01-30 11:52发布

I'm trying to pass the entered text to the controller using an ajax request. But i'm getting athe error "Uncaught TypeError: Cannot set property 'value' of null " when I tried to execute JS file..

Here is the HTMLcode:

<form action="">
    <input type="text" class="searchbox1" name="search" placeholder="Search for Brand, Store or an Item..." value="text" />
    <input type="button" class="searchbox_submit1" name="submit" value="text" onClick="javascript:getSearchText();">
</form>

Here is the JS code:

function getSearchText() {
    var searchText = document.getElementByName("search").value;
    h_url=document.getElementById("u").value;
    var theURL = h_url+'search_all/' + deptid + '/' + searchText + '/1';
    $.ajax({
        url : theURL,
        fail: function(){
        },
        success : function() {
        },
        error:function(){
        }
    });
}

Please help me to fix this.

8条回答
做自己的国王
2楼-- · 2020-01-30 11:58

You don't have an element with the id u.That's why the error occurs. Note that the global variable document.getElementById("u").value means you are trying to get the value of input element with name u and its not defined in your code.

查看更多
Anthone
3楼-- · 2020-01-30 12:01

guys This error because of Element Id not Visible from js Try to inspect element from UI and paste it on javascript file:

before :

document.getElementById('form:salesoverviewform:ticketstatusid').value =topping;

After :

document.getElementById('form:salesoverviewform:j_idt190:ticketstatusid').value =topping;

Credits to Divya Akka .... :)

查看更多
劫难
4楼-- · 2020-01-30 12:06

h_url=document.getElementById("u") is null here

There is no element exist with id as u

查看更多
女痞
5楼-- · 2020-01-30 12:11

In case anyone landed on this page for a similar issue, I found that this error can happen if your JavaScript is running in the HEAD before your form is ready. Moving your JavaScript to the bottom of the page fixed it for my situation.

查看更多
家丑人穷心不美
6楼-- · 2020-01-30 12:17

The problem may where the code is being executed. If you are in the head of a document executing JavaScript, even when you have an element with id="u" in your web page, the code gets executed before the DOM is finished loading, and so none of the HTML really exists yet... You can fix this by moving your code to the end of the page just above the closing html tag. This is one good reason to use jQuery.

查看更多
成全新的幸福
7楼-- · 2020-01-30 12:17

It seems to be this function

h_url=document.getElementById("u").value;

You can help yourself using some 'console.log' to see what object is Null.

查看更多
登录 后发表回答