Javascript change id from form input - javascript

I am working on a new project and I ran into one issue
I want to have a form where the user can enter their username so a 3d image is generated.
The code for the image generator is:
<span class="mc-skin" data-minecraft-username="UsernameHere"></span>
and what I need is a input field that changed the data-minecraft-username to the input of the form.
Thanks for any help!

you can try this:
var user="Zane";
document.getElementsByClassName("mc-skin")[0].setAttribute('data-minecraft-username',user);
But it will be better if you will use id for that particular span and set it like this:
add id="spanId" then use
document.getElementById('spanId').setAttribute('data-minecraft-username', user);

You can use HTML 5
Example:
variable.setAttribute('data-minecraft-username','randomUserName');
variable beeing your span element
More reference here: http://html5doctor.com/html5-custom-data-attributes/

Probably the most robust way to deal with data-* attributes is to use setAttribute and getAttribute. If the span has an id of Skin, then you might use:
var span = document.getElementById('Skin');
span.setAttribute('data-minecraft-username', newValue);
You can also use the element.dataset property:
span.dataset['minecraft-username'] = newValue;
Which will add a data-minecraft-unsername attribute with a value of whatever is in newValue. However, support may be lacking in older browsers (see MDN HTMLElement.dataset, which indicates fairly recent browsers such as IE 11, Safari 6, etc. are required).
Also see MDN Using data attributes.
To use the above script in a document, you might do something like:
<script>
function setDataAttribute(elID, attName, value) {
var el = document.getElementById(elID);
if (el) {
el.setAttribute('data-' + attName, value);
}
}
function setContent(elID, value) {
var el = document.getElementById(elID);
if (el) {
el.innerHTML = value;
}
}
</script>
<span id="Skin"></span>
<br>
<input type="text" onblur="
setDataAttribute('Skin', 'minecraft-username', this.value);
setContent('Skin', this.value);
">

Related

How to use jQuery to select deeply nested elements created dynamically with javascript

So I have an object in my code and I use js to add the properties of the object to an array named rec based on users interaction. then I use a function named unRec to get unique elements of the array. Then I add the values returned by unRec to the HTML. Then I use jquery to wrap each of the values in anchor tags. So the code is basically like this
obj= {
0: "<span>module1</span>",
1: "<span>module1</span>",
2:"<span>module1</span>",
3:"<span>module2</span>",
4:"<span>module2</span>",
5:"<span>module3</span>",
6:"<span>module3</span>",
7:"<span>module3</span>",
8:"<span>module3</span>",
9:"<span>module4</span>"
}
function unRec(arr){
preRec = [];
for (j of arr){
if (preRec.indexOf(j)=== -1) {
preRec.push(j);
}
}
return (preRec);
}
Recom.innerHTML = unRec(rec);
$('#congrat #recom span').wrap('')
Now am unable to select the created anchors. Hence this function doesn't work
$('#congrat #recom .disp').click(function(e) {
var url = $(this).attr('href') + '#' + $(this).text();
$('#module').html('loading...).load(url); e.preventDefault();
});
I have tried to use find to select the anchors but it still doesn't work. This is the test
var t = $('#congrat #recom').find ('a').length;
console.log(t);
The HTML is basically like this:
<div id="congrat">
<span id="recom"></span>
</div>
<div id="module">click on one of the modules above<div>
Please provide a solution to select the created anchors. Thanks in advance

Using html <template>: innerHTML.replace

The most popular intro says that I can easily clone html templates within my document.
<template id="mytemplate">
<img src="" alt="great image">
<div class="comment"></div>
</template>
The word "template" however implies that you won't copy-paste it as is, unmodified. Template means that you want to update some variables with specific values. It recommends the following approach for updating the node:
var t = document.querySelector('#mytemplate');
// Populate the src at runtime.
t.content.querySelector('img').src = 'logo.png';
var clone = document.importNode(t.content, true);
document.body.appendChild(clone);
Isn't it perfect? There is querySelector to get the element so that you can update its attributes. I just do not understand why does he updates the template before cloning it. But that is not my question. The real question is that, in mine case, the location of variable to update is unknown. It can be either attribute or innerText in whatever template structure is. This is the most general and frequent use of template, I believe. So, I can ensure that the variable id is unique within the template, like #reply here
<template id="comment-template">
<li class="comment">
<div class="comment-author"></div>
<div class="comment-body"></div>
<div class="comment-actions">
Reply
</div>
</li>
</template>
ought to update the #reply, but author does not explain how to do that. I succeeded to use innerHTML on the original template, document.querySelector('#mytemplate').innerHTML.replace(id, value) but this breaks the template for later use, as explained above. I failed to update the cloned text. This is probably because template.clone produces a document fragment, which has no innerHTML. But, before pushing that forth, I decided to investigate for alternatives since I know that innerHTML/outerHTML is not quite standard.
Alternative for innerHTML? inspects the alternatives to innerHTML but again, they assume too much about the template. Instead of just replacing some specific identifiers with user values, they completely recreate the template, which defeats the whole notion of template. Template looses any sense once you recreate its whole code in the variable valuation. So, how is <template> is supposed to use?
Here is mine solution, the valuate function
<div id="div1">env: </div>
<template id="template1">
var1=var2
</template>
<script language="javascript">
function valuate(template, targetParent, dict) {
var t = document.querySelector('#' + template);
var clone = t.cloneNode(true)
for (key in dict) {
clone.innerHTML = clone.innerHTML.replace(key, dict[key])
}
var fragment = document.importNode(clone.content, true)
var canvas = document.querySelector('#' + targetParent);
canvas.appendChild(fragment);
//alert(canvas.innerHTML)
}
valuate("template1", "div1", {var1:"1+1", var2:2, "#ref":"abc.net"})
</script>
It takes the template, dictionary and target element. Unfortunately, it fails for SVG hierarchies. Don't you know why?
Using again <template>.querySelectorAll to select the element and setAttribute to change the href value
var a = <template>.querySelectorAll("a[href='#reply']");
a[0].setAttribute("href", <url>)
This is a more generic function. It changes an attribute of the selected elements within a cloned template, of course this is very basic,
//object = the cloned template.
//selector = the selector argument which selects all nodes.
//attribute = the attribute to change.
//value = the value that needs to be set to the attribute.
function changeTemplateValues(object, selector, attribute, value)
{
elements = object.querySelectorAll(selector);
if (elements.length == 0)
{
return false; //stop executing. No elements were found.
}
else if (!attribute && !value)
{
return elements; //no attributes and values are set, return nodelist;
}
else
{
if (attribute)
{
//loop over all selected elements to change them.
for (var i = 0; i < elements.length; ++i)
{
if (attribute.match(/innerHTML|textContent|text|nodeValue/g) )
{
elements[i][attribute] = value;
}
else
{
elements[i].setAttribute(attribute, value);
}
}
}
else
{
//No attribute return false;
return false;
}
}
}

How to update 'src' attributes of multiple images?

I have the following source:
<body>
<div class="slideshow_top">
<img class="slideshow_image" src="img/cycle/putritos.jpg">
</div>
<div class="slideshow_mid">
<img class="slideshow_image" src="img/cycle/stage.jpg">
</div>
<div class="slideshow_bot">
<img class="slideshow_image" src="img/cycle/marketing.jpg">
</div>
...
</body>
Assuming I have three generated new src values such as:
var src1="img/cycle/newimage1.jpg
var src2="img/cycle/newimage2.jpg
var src3="img/cycle/newimage3.jpg
How can I change the source values of the already existing images? I'm unsure because I know the surrounding divs of the images are uniquely named, but the class of the images themselves are shared. Is it still possible to update each source attribute with Javascript given this?
Looks like part of your question has to do with selecting images only if they are a child of a slideshow_top/mid/bot div element. There's a few ways to do this...
In jQuery, you could do this:
$('.slideshow_top img').attr('src',src1);
$('.slideshow_min img').attr('src',src2);
//etc.
That's just a simple Sizzle CSS-style selector. You can also use jQuery's .children() method, if you want:
$('.slideshow_top').children('img').attr('src',src1);
In plain old JavaScript it's a little more wordy, but you can still do it:
var slideShowTop = document.getElementsByClassName('slideshow_top'),
slideShowTopImage = slideShowTop[0].getElementsByTagName('IMG');
slideShowTopImage[0].setAttribute('src',src1);
//etc.
Note though, that getElementsByClassName isn't supported in version of IE less than 9, so you'll have to write your own little function to, say, loop through all elements by tag name and filter them by className, etc. jQuery might be the way to go on this one...
You can do something like:
var new_images = $.map([1,2,3], function(x) { return "newimage" + x + ".jpg"; })
$("img").each(function(i, x) { x.src = new_images[i]; })
var src_array=["img/cycle/newimage1.jpg","img/cycle/newimage2.jpg","img/cycle/newimage3.jpg"]
$(".slideshow_image").each(function(index){
$(this).attr("src",src_array[index])
})
Try
.each( function(index, Element) )
Iterate over a jQuery object, executing a function for each matched element.
//create array of images
var arrSrc = ['img/cycle/newimage1.jpg','mg/cycle/newimage2.jpg','img/cycle/newimage3.jpg'];
$('.slideshow_bot .slideshow_image').each(function(i, el){ //to loop through images
el.prop('src',arrSrc[i]); //set image here
});
.prop( propertyName, value )

how to get outerHTML with jquery in order to have it cross-browser

I found a response in a jquery forum and they made a function to do this but the result is not the same.
Here is an example that I created for an image button:
var buttonField = $('<input type="image" />');
buttonField.attr('id', 'butonFshi' + lastsel);
buttonField.val('Fshi');
buttonField.attr('src', 'images/square-icon.png');
if (disabled)
buttonField.attr("disabled", "disabled");
buttonField.val('Fshi');
if (onblur !== undefined)
buttonField.focusout(function () { onblur(); });
buttonField.mouseover(function () { ndryshoImazhin(1, lastsel.toString()); });
buttonField.mouseout(function () { ndryshoImazhin(0, lastsel.toString()); });
buttonField.click(function () { fshiClicked(lastsel.toString()); });
And I have this situation:
buttonField[0].outerHTML = `<INPUT id=butonFshi1 value=Fshi src="images/square-icon.png" type=image jQuery15205073038169030395="44">`
instead the outer function I found gives buttonField.outer() = <INPUT id=butonFshi1 value=Fshi src="images/square-icon.png" type=image>
The function is:
$.fn.outer = function(val){
if(val){
$(val).insertBefore(this);
$(this).remove();
}
else{ return $("<div>").append($(this).clone()).html(); }
}
so like this I loose the handlers that I inserted.
Is there anyway to get the outerHTML with jquery in order to have it cross-browser without loosing the handlers ?!
You don't need convert it to text first (which is what disconnects it from the handlers, only DOM nodes and other specific JavaScript objects can have events). Just insert the newly created/modified node directly, e.g.
$('#old-button').after(buttonField).remove();`
after returns the previous jQuery collection so the remove gets rid of the existing element, not the new one.
Try this one:
var html_text = `<INPUT id=butonFshi1 value=Fshi src="images/square-icon.png" type=image jQuery15205073038169030395="44">`
buttonField[0].html(html_text);
:)
Check out the jQuery plugin from https://github.com/darlesson/jquery-outerhtml. With this jQuery plugin you can get the outerHTML from the first matched element, replace a set of elements and manipulate the result in a callback function.
Consider the following HTML:
<span>My example</span>
Consider the following call:
var span = $("span").outerHTML();
The variable span is equal <span>My example</span>.
In the link above you can find more example in how to use .outerHTML() plug-in.
This should work fine:
var outer = buttonField.parent().html();

"defaultValue" property for <select>?

Javascript has textObject.defaultValue=somevalue for retrieving the default value (stored value from page load) of an input even if you wipe the input and replace the contents, you can still get the default back. Like this:
// in the html page
<input id="addr1" type="text" value="21 Oak St." />
// the jquery
myInput = $("#addr1"); // the input, default value on page load = 21 Oak St.
$(myInput).val('51 New St'); // wipe default and set new
// alerts 21 Oak St
alert($(myInput).val($(myInput)[0].defaultValue));
How do you accomplish this on a select?
selectedIndex is boolean, not the value, so that does not work.
Thanks!
You probably want to look at the "defaultSelected" attribute of "option" elements.
Initially, "defaultSelected" will be true if the original HTML of the option tag had an explicit "selected" attribute. You can change that by setting the attribute on option tags with Javascript after the page has loaded, in response to whatever conditions you like.
This is the jquery that works for me:
$('select[name="name_of_select"] option[selected]').val()
with Jquery we can do sth like this :
$('select[name="type_id"] option').map(function()
{
if($(this).attr('defaultSelected')==true) return this
}).get(0).value;
This will return the default Selected option value
:)
I used the following to loop through a forum, check their default values and their current values.
if the script comes a cross a single selectbox it will loop through the children on the selectbox.
oFormObject = document.forms[0];
for(i=0; i<oFormObject.elements.length; i++)
{
oValue = oFormObject.elements[i].value;
oType = oFormObject.elements[i].type;
if(oType=='select-one') {
for(k=0; k<oFormObject.elements[i].children.length; k++)
{
if(oFormObject.elements[i].children[k].defaultSelected==true){
oformElement = oFormObject.elements[i].children[k].value;
}
}
}else{
oformElement = oFormObject.elements[i].defaultValue;
}
console.log(oformElement);
console.log(oValue);
console.log(oType);
}
there may be multiple "selected" option elements, in that case pick the first if no other requirements are set. #Pointy tip is correct but be aware that the "defaultValue" property can be overwritten by other code in the same page. If it were read-only it would be more useful :-)
I found a shortest way to do this :
$('select#myselect').find('option[defaultSelected]');
I run this on page load to manually set the defaultValue for Select boxes.
// Set a default value property on selectboxes (for reverting)
$('select').each(function(index,ele) {
var origvalue = $(this).val(),
defaultvalue = $(this).prop('defaultValue');
// If the default value hasn't already been set for this selectbox
if(!defaultvalue) {
$(this).prop('defaultValue', origvalue);
}
});
The simplest way to do this is:
$('#selectbox option').prop('selected', function() {
return this.defaultSelected;
});

Categories

Resources