سؤال

Trying to use phantomjs to do a query on a form that has a text field with name "category" and a button with value "search", the following script will cause the button to be pressed, which triggered a POST message to be sent. However, in the POST message, I don't see the value for category.

var page = require('webpage').create();

page.open('http://www.example.com', function() {
  page.includeJs("http://ajax.googleapis.com/ajax/libs/jquery/1.6.1/jquery.min.js", function() {
    page.evaluate(function() {
       $('input[name="category"]').value = "tmp1";
        console.log($('input[name="category"]').value);
        $('input[value="search"]').click();
    });
    //phantom.exit()
  });
});

If I do the following two lines on chrome browser developer console manually, the HTTP POST message sent does contain the right value for category field. Any idea what went wrong? Thanks.

$('input[name="category"]').value = "tmp1";
$('input[value="search"]').click();
هل كانت مفيدة؟

المحلول

Use .val() to update the value of a form field with jQuery.

$('input[name="category"]').val("tmp1");

نصائح أخرى

The problem is that $('input[name="category"]') returns a jQuery node list (like an array). So you need to select the first one to access the value attribute:

$('input[name="category"]')[0].value = "tmp1";
console.log($('input[name="category"]')[0].value);

The change is [0].

مرخصة بموجب: CC-BY-SA مع الإسناد
لا تنتمي إلى StackOverflow
scroll top