1

I'm trying to use jquery to set the value of some tags. This is for a the admin side of a wordpress widget which will store a list of records, keyed by a date that are retrieved by using a <select>. In order to achieve this I'm having to to some janky value storage in data-* attributes to link the contents of three hidden <select> lists.

The idea is that the hidden list's values are retrieved by grabbing the visible <select>'s selected <option>'s data-date attribute value and grabbing the <option> in each hidden <select> that has a matching data-date. These values are then put into <input> fields for the user to edit.

HTML fragment

<label for="spdates">Special Dates:</label>

<p>
  <select id="spdates">
    <option data-date='new' value='new'>New Date</option>
    <option data-date='23/05/1992' value='23/05/1992'> 23/05/1992-jake</option>
    <option data-date='15/08/1997' value='15/08/1997'> 15/08/1997-rebecca</option>
    <option data-date='17/03/1995' value='17/03/1995'> 17/03/1995-clive</option>
  </select>
</p>
<p>
  <label for="spname">Special Name:</label>
  <input class="widefat namspani" id="spname" type="text" value="" />
</p>
<p>
  <label for="sptext">Special Text:</label>
  <input class="widefat namspani" id="sptext" type="text" value="" />
</p>
<p>
  <label for="spdate">Special Date(dd/mm/yyyy):</label>
  <input class="widefat namspani" id="spdate" type="date" value="" />
</p>
<p>
  <label for="spimage">Special Image:</label>
  <br />
  <input type="text" class="img anisp" id="spimage" value="" />
  <input type="button" class="select-imgsp" value="Select Image" />
</p>

<select id="eventNames" name='widget-dates_widget[__i__][eventNames][]' multiple hidden>
  <option data-date='23/05/1992' value='[23/05/1992]jake' selected> jake</option>
  <option data-date='15/08/1997' value='[15/08/1997]rebecca' selected> rebecca</option>
  <option data-date='17/03/1995' value='[17/03/1995]clive' selected> clive</option>
</select>
<select id="eventText" name='widget-dates_widget[__i__][eventText][]' multiple hidden>
  <option data-date='23/05/1992' value='[23/05/1992]yay me' selected> yay me</option>
  <option data-date='15/08/1997' value='[15/08/1997]rebecca' selected> rebecca</option>
  <option data-date='17/03/1995' value='[17/03/1995]clive' selected> clive</option>
</select>
<select id="eventImages" name='widget-dates_widget[__i__][eventImages][]' multiple hidden>
</select>

Jquery function

$(function() {

  //onchange for the date select to populate the other boxes
  $(document).on('change', 'select#spdates', function(evt) {
    var date = $(this).find(":selected").attr("data-date");
    if (date == "new") {
      //new date selected, discard what's in the boxes and blank values
      $(".namspani").val("");
    } else {
      //different date selected, discard what's in the boxes and blank values
      alert($("#eventNames").find("[data-date='" + date + "']").text());
      $("#spname").val($("#eventNames").find("[data-date='" + date + "']").text()); //grab from other lists
      $("#sptext").val($("#eventText").find("[data-date='" + date + "']").text());
      $("#spdate").val(date);
      $("#spimage").val($("#eventImagess").find("[data-date='" + date + "']").text());
    }
  });
})

I've confirmed my code is being run as I've put an alert() containing one of the values I'm trying to set in the branch of the function i expect to run. In practice the alert files, with the right content, however the input fields don't fill with data.

This code works in jsfiddle https://jsfiddle.net/ForceGaia/j363mv3w/1/ but not natively in firefox or chrome.

What is going on? I'm fairly new to jquery, so I'm now wondering if I'm missing something basic.

EDIT:

The alert fires, so i know it's getting to the right chunk of code, thus some version of JQuery seems to be working. console.log($().jquery); puts 1.12.4 to the log.

I tried putting hardcoded strings into the .var() parameters, still nothing.

I moved the $("#spname") search into a variable to see if it was finding it.

var spnamedom = $("#spname");

After that chunk of code spnamedom was an array of elements (which, knowing jQuery, i expected) I tried accessing the 0th element and it was the correct element.

so i tried both of the following

var spnamedom = $("#spname");
spnamedom.val("a thing");

And

var spnamedom = $("#spname")[0];
spnamedom.val("a thing");

spnamedom is always what I'm expecting, but neither work. There is an element with the correct id in both cases, either as the 0th element, or straight in the variable.

he latter puts TypeError: spnamedom.val is not a function to the log. I assume that error is because I'm no longer in a JQuery object and am looking at a DOM object after i grabbed the 0th element. I could possibly edit this raw DOM element to get what I want, but the initial question remains, why does my code work in jsfiddle, but not a live browser; as from the reading I'm doing, this should work.

I have also found jQuery .val change doesn't change input value and using `.attr('value','text') doesn't work either.

EDIT 2

I realised that in my code i have something that does what i want already on different controls, and it works - which is even more bewildering. I had totally forgotten that the code was performing the same action when it came down to it.

Before i only supplied an exerpt of my JQuery script, here's the entire thing

var image_field;
jQuery(function($) {
    $(document).on('click', 'input.select-img1', function (evt) {
        image_field = $(this).siblings('.img');
        tb_show('', 'media-upload.php?type=image&amp;TB_iframe=true');
        return false;
    });
    $(document).on('click', 'input.select-img2', function (evt) {
        image_field = $(this).siblings('.img');
        tb_show('', 'media-upload.php?type=image&amp;TB_iframe=true');
        return false;
    });
    $(document).on('click', 'input.select-img3', function (evt) {
        image_field = $(this).siblings('.img');
        tb_show('', 'media-upload.php?type=image&amp;TB_iframe=true');
        return false;
    });
    $(document).on('click', 'input.select-imgsp', function (evt) {
        image_field = $(this).siblings('.img');
        tb_show('', 'media-upload.php?type=image&amp;TB_iframe=true');
        return false;
    });

    window.send_to_editor = function (html) {
        imgurl = $('img', html).attr('src');
        image_field.val(imgurl);
        tb_remove();
    }

   // onchange for the date select to populate the other boxes
    $(document).on('change', 'select#spdates', function (evt) {
        console.log($().jquery);
        var date = $(this).find(":selected").attr("data-date");
        if (date=="new") {
            //new date selected, discard what's in the boxes and blank values
            $(".namspani").val("");
        }
        else {
            //different date selected, discard what's in the boxes and blank values
            alert($("#eventNames").find("[data-date='"+date+"']").text());
            var spnamedom = $("#spname");
            spnamedom.attr('value', 'new value'); //grab from other lists
            $("#sptext").val($("#eventText").find("[data-date='"+date+"']").text());
            $("#spdate").val(date);
            $("#spimage").val($("#eventImagess").find("[data-date='"+date+"']").text());
        }
    });
});

the code i didn't include is acts on bits of html that look like this

<p>
    <label for="s3image">Image 3:</label><br />
    <input type="text" class="img ani1" name="widget-namsoc_nextmeet_widget[__i__][s3image]" id="s3image" value="" />
    <input type="button" class="select-img3" value="Select Image" />
</p>

What it does is open the Wordpress image uploader dialog when you click a button. When "insert into post" is pressed it sets the path value into the field.

This code works. So what is so different to the other code that makes it fail?

Force Gaia
  • 514
  • 2
  • 8
  • 24
  • in your jsfiddle you forget to add jQuery, after that value is set – uingtea May 30 '17 at 21:03
  • How about this: https://jsfiddle.net/fhqdns8c/ (moved the "database" from HTML to JS) –  May 30 '17 at 21:17
  • What happens if you hard-code vals, say ``$("#spname").val("A"), `...("B")`, `...("C")`, `...("D")`? – Roamer-1888 May 30 '17 at 21:23
  • @ChrisG - the "database" needs to be in form controls as this is passed to the wordpress $instance in the back end. the "janky" stuff i refer to is that the ` – Force Gaia May 30 '17 at 21:38
  • @Roamer-1888 Same issue: alert() fires, but the hardcoded value doesn't get put in the field. which would suggest that jquery isn't finding the DOM objects in my version live in a browser, while something that jsfiddle is doing is compensating – Force Gaia May 30 '17 at 21:41
  • I managed to breakpoint the part of it after the alert() (totally forgot that was a thing that could be done) and stored the result of the query in a variable. It appeared to be an array so i looked and found the 0th element was the one i was after - so it IS finding it in my live version. I changed the code to do the val() assignment to the 0th element as i thought that was it, but it still doesnt work. – Force Gaia May 30 '17 at 21:53
  • I jsut noticed the downvote, why? I'm providing applicable code, answering the questions, performing troubleshooting steps as asked. I've looked at sources and am just confused by a disparity that doesn't seem aparent to someone unfamiliar with the framework. – Force Gaia May 30 '17 at 22:08
  • Ignore the downvote - they are awarded far too liberally here. – Roamer-1888 May 30 '17 at 22:22
  • Just to check that `$` is still `jQuery`, try `console.log($().jquery);` inside change handler. – Roamer-1888 May 30 '17 at 22:24
  • @Roamer-1888 output form that call is 1.12.4. but i did find out a few things so I'm going to update the question in a bit with extra steps. – Force Gaia May 30 '17 at 22:51
  • jQuery version 1.12.4 should do everything asked of it here. I just tried v 1.9.1 in the fiddle and it worked OK. – Roamer-1888 May 30 '17 at 23:05
  • now you see my frustration. see my edit for further tests i've done – Force Gaia May 30 '17 at 23:19
  • Try inspecting the input elements - right-click one and select "Inspect". See if the id is what you expect. – Roamer-1888 May 30 '17 at 23:29
  • I've kept the inspector up the entire time. and i've found another question with a similar issue, but that solution doesn't work either (see new edit). If i edit the attribute in the inspector, it works, but it seems the JavaScript can't touch it. I'm beginning to think some other wordpress script is the culprit, but why would it do this? I'll try this in a plain php page tomorrow morning to eliminate wordpress from the equation, and report back. – Force Gaia May 30 '17 at 23:40
  • I agree, Wordpress seems to be at play here though it's hard to see what it might be doing. – Roamer-1888 May 30 '17 at 23:47
  • Have you tried without jQuery yet? `document.getElementById('spname').value = 'x';` ? Or `$("#spname").get()[0].value = 'x';` ? –  May 31 '17 at 10:00
  • @ForceGaia, make sure the ids, `spname`, `sptext` etc., are unique. Duplicates would certainly screw things up. – Roamer-1888 May 31 '17 at 12:12
  • I've jsut tried plain javascript attached to the `onchange` attribute - no difference. id is unique as the item I'm getting matches what i have perfectly in terms of other attributes – Force Gaia May 31 '17 at 12:40
  • It's got to be something simple. Just a question of tracking it down. – Roamer-1888 May 31 '17 at 19:47
  • indeed, and thanks for the ongoing troubleshooting. I've been googling for interactions with wordpress but i'm finding nothing; and chrome's "global listeners" only lists my function as a listener – Force Gaia May 31 '17 at 22:55
  • Another edit. I realised there was some code that already did the .val() operation that worked, so there must be something fundamentally wrong with my new function. – Force Gaia Jun 01 '17 at 19:59

0 Answers0