简体   繁体   中英

Can't set value of input field inside jquery UI dialog

I'm trying to change the value of input field with jquery. The input field is inside UI dialog box. It's part of my zend form

<input name="formulaCategory" id="formulaCategory" value="" size="40" type="text">

I have a link calls for a function that shows the dialog and I want it to change the value of this input as well.

function editFormulaCategoryDialog() {

    $("#edit-formula-category-dialog").dialog({show: "slide"});
    $("#formulaCategory").val('test');
}

Why it doesn't work?

If I put the input code somewhere else on the page outside dialog box and click the same link the dialog box shows up and the value of input field outside dialog is changed as expected.

Try this:

function editFormulaCategoryDialog() {

    $("#edit-formula-category-dialog").dialog({
        show: "slide",
        create: function() {
            $("#formulaCategory").val('test');
        }
    });
}

Try with a callback after dialog box create . You can also use open event callback.

Jquery UI on run time removes the all document objects and puts it out side the DOM at this time none of the objects will be accessible for you . Thats the default behavior of all Jquery UI plugins . So you have to bear that some how by changing the way you are using it .

And also there is no way to get dialog to leave your elements alone as it would be impossible to properly display the dialog. You will have to have to use the dialog callback methods to dynamically populate hidden fields inside your form, or something similar if you want to use this pattern of showing part of your form in a dialog.

I needed similar solution, tried using setTimeout function with small latency. It worked for me.

function myCreateDialogFn(){
    //.....create jQuery Dialog here;

    setTimeout(function () {
        $("#edit-formula-category-dialog").find('input').each(function () {
            if (this.name=="formulaCategory"){
                // your code here
            }
        }
    }, 200);
}

I do it this way instead of using an arbitrary timeout. I have function that polls for the existence of the element every 250ms.

// wait for element to exist before populating
function waitForElement(elementPath, callBack){
  window.setTimeout(function(){
    if($(elementPath).length){
      callBack(elementPath, $(elementPath));
    }else{
      waitForElement(elementPath, callBack);
    }
  },250)
}

then I call it like this

  waitForElement("#idOfDialog",function(){
            var ordered=$("#input1).val();
            var price=$("#input2").val();
            var vendor=$("#input3").val();
.... or set value
             $("#input4").val("test");

and that seems to solve the problem

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM