1

I have a select element and i wanna take some custom data from this. I don't know if this syntax is right but is possible to get the data??

<select data-select="placeholder:This is title; width:300px; dissabled; hidden;"></select>

If the attribute have inside colon [ : ] , the left part i wanna use it something like new attribute and the right part as the value of this
The semicolon [ ; ] is used to break this new attributes
The logic is like the style attribute

The code i wanna have this form:

$("[data-selectlist]").each(function(){
    var $ul = $("<ul/>", {
        'placeholder': $(this).attr('placeholder'),
        'width' : $(this).attr('width')
    });
    .
    .
    .
});

With what i can replace the .attr() to have the desired result??

5
  • Your "jQuery to get the data like this" has nothing to do with your question. Try to be more specific. Show the JS that actually gets some data. Describe your desired output. Please read How to Ask. Commented Aug 19, 2018 at 13:14
  • I made some changes. Is better now?? Commented Aug 19, 2018 at 13:46
  • Now seems definitely better! Commented Aug 19, 2018 at 14:04
  • I'm just confused why on earth would you ever want to make a <ul> element hidden, disabled etc. An <ul> cannot be disabled and have width attribute :) Commented Aug 19, 2018 at 14:08
  • It was just to test non colon attributes. I wanna create a custom select option with full features xD Commented Aug 19, 2018 at 14:42

1 Answer 1

1
  • Access every $("[data-select]") element .attr("data-select")
  • iterate the value and create an object like {attr1:val, attr2:val}
  • Apply the created attributs object to the same (or some) element: $(this).attr(attrObj) or $("<ul/>", {attr: attrObj})

$("[data-select]").attr("data-select", function(i, data) {

  if ( !data ) return; // Early return
  
  // Convert data values to attributes object
  const attrObj = data.match(/(?!\s)[^;]+/g).reduce((acc, cur) => {
    const p = cur.split(":");
    acc[p[0]] = p[1] || p[0];
    return acc;
  }, {});

  console.log(attrObj);
  
  // Apply attributs object to element
  $(this).attr(attrObj)

});
Select is now hidden! Inspect element to see the attributes applied!<br>
<select data-select="placeholder:This is title;   width:300px; disabled; hidden;">
  <option>test</option>
</select>

<script src="//code.jquery.com/jquery-3.3.1.min.js"></script>

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.