Passing dynamic values to a jQuery Plugin - javascript

The jQuery plugin is looking for some value to set:
$('.toClone_example88888').metalClone({
position:'after',
btnClone : '.btn_toClone_example88888'
});
The problem is the class names for the item to be cloned, and the corresponding button will be coming from a database so the values need to be dynamic.
I've tried this and while it did not work, it did not produce any console errors either. What am I missing or is this even possible to do?
I found this SO question and believe it has the same core components (Sending dynamic variable to jquery) but applying those same concepts didn't work with my implementation.
$('.cloneBtn').on('click', function(){
var getDestinationOfWhereClonedCopyShouldGo = $(this).data("destinationclone");
$('#' + getDestinationOfWhereClonedCopyShouldGo).metalClone({
position:'after',
btnClone : '.cloneBtn'
});
});
I also tried this but same this, didn't work but no error message either:
var cloneThis = function(){
$('.cloneBtn').on('click', function(){
var getDestinationOfWhereClonedCopyShouldGo = $(this).data("destinationclone");
putCloneHere(getDestinationOfWhereClonedCopyShouldGo);
});
}
var putCloneHere = function(element){
$('#' + element).metalClone({
position:'after',
btnClone : '.cloneBtn'
});
}
Additional HTML as requested:
<div id="firstOne">
<input type="text">
<select id="m">
<option value="">--Please Select</option>
<option value="Hello">Hello</option>
</select>
</div>
<div class="container_body">
<input type="button" class="cloneBtn" value="Create New Copy" data-destinationclone="firstOne">
</div>
<div id="secondOne">
<input type="text">
<select id="m">
<option value="">--Please Select</option>
<option value="Hello">Hello</option>
</select>
</div>
<div class="container_body">
<input type="button" class="cloneBtn" value="Create New Copy" data-destinationclone="secondOne">
</div>
Here is a jsfiddle (which includes the plugin code).

Related

Clone or Add more fields using jquery including the functionality

So I have a select group of reason and other select-group for subreason. I want to add more reason but as soon as I click on the button the same field appear but it changes the value of above fields too. I need them to be independent but also perform the (reason -subreason).
Code
<div class="tab" id="add_reason">
<h4 class="card-title">Reason</h4><Br>
<label for="roads">Select Branch</label>
<select name="reason[]" id="reason" class="form-control required">
<option value="">Reasons</option>
<option class="road" value="Road">Road</option>
<option class="driver" value="Driver">Driver's Fault</option>
</select><br>
<select id="subreason" name="subreason[]" class="form-control">
<optgroup label="Road" required>
<option>Pot Holes</option>
<option>No boards at starting and ending point of Bridge</option>
<option>No Painting to Divider</option>
<option>Speed Breaker without Zebra Crossing</option>
</optgroup>
<optgroup label="Driver" required>
<option>Lane Cutting</option>
<option>Overtaking from Wrong side</option>
<option>Corner Overtaking</option>
</optgroup>
</select>
<button type="button" class="btn btn-primary" id="btn-reason">Add Reasons</button>
</div>
Script
$(document).ready(function(){
var $optgroups = $('#subreason > optgroup');
$("#reason").on("change",function(){
var selectedVal = this.value;
$('#subreason').html($optgroups.filter('[label="'+selectedVal+'"]'));
});
});
$(document).ready(function(){
$("#btn-reason").click(function(){
$('#add_reason').clone(true).appendTo('#add_reason');
});
});
The first thing to know about jQuery .clone() is that it creates new DOM elements from some existing ones.
That implies the same rules as any other dynamically created elements:
Do not use ids
Delegate event handlers
Additionnally, the cloned set of elements cannot be appended multiple places... So, to use it as a templating trick, you have to clone twice. Once on page load (to save them before any change occurs) and once again when appending somewhere.
$(document).ready(function() {
// Cloned "templates"
let reason_wrapper = $(".reason-wrapper").clone()
var $optgroups = $(".subreason > optgroup").clone()
// "delegated" event handler for any existing or future .reason element
$(document).on("change", ".reason", function() {
var selectedVal = this.value;
$(this)
.closest(".reason-wrapper")
.find(".subreason")
.html($optgroups.clone().filter('[label="' + selectedVal + '"]'));
});
// "delegated" event handler for any existing or future .btn-reason element
$(document).on("click", ".btn-reason", function() {
reason_wrapper.clone().appendTo("#add_reason");
});
});
.reason-wrapper {
margin-top: 1em;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div class="tab" id="add_reason">
<h4 class="card-title">Reason</h4>
<div class="reason-wrapper">
<label for="roads">Select Branch</label>
<select name="reason[]" class="reason form-control required">
<option value="">Reasons</option>
<option class="road" value="Road">Road</option>
<option class="driver" value="Driver">Driver's Fault</option>
</select>
<br>
<select name="subreason[]" class="subreason form-control">
<optgroup label="Road" required>
<option>Pot Holes</option>
<option>No boards at starting and ending point of Bridge</option>
<option>No Painting to Divider</option>
<option>Speed Breaker without Zebra Crossing</option>
</optgroup>
<optgroup label="Driver" required>
<option>Lane Cutting</option>
<option>Overtaking from Wrong side</option>
<option>Corner Overtaking</option>
</optgroup>
</select>
<button type="button" class="btn btn-primary btn-reason">Add Reasons</button>
</div>
</div>

How to append a dropdown list before a button?

So I have a div that holds a dropdown list of items. I want the user to add more dropdown list's by pressing a button.
I managed this, but the problem I'm facing is that the new list gets appended after the button. I want the button to be always underneath the dropdown list.
I know that there is an option called insertBefore(), but I don't really know how to use it correctly in my case.
Oh and by the way, do you guys have any thoughts about how to give each new dropdown list a unique name? Because it is a form that I am planning on sending later on. I think I need to work with counters in my script file, but I om not sure yet.
So the HTML:
<form role="form" class="contact-form" id="contact-form" method="post">
<div class="form-group">
..not important for the question...
</div>
<div class="form-group">
<div class="controls" id="dropdown_item">
<select class="offerte_product" name="product_1">
<option value="volvo">Volvo</option>
<option value="saab">Saab</option>
<option value="opel">Opel</option>
<option value="audi">Audi</option>
</select>
<input id="add_option" type="submit" value="Add More" onclick="return false" />
</div>
</div>
<div class="form-group">
..not important for the question...
</div>
And the script I am using is:
<script>
$(function(){
$('#add_option').on('click',function(){
var r= $('<select class="offerte_product" name="product_2"> <option value="volvo">Volvo</option> </select> ');
$("#dropdown_item").append(r);
});
});
So do I need to put insertBefore somewhere before the append(r)? I really have no clue.
Just put the button outside the div:
<div class="controls" id="dropdown_item">
<select class="offerte_product" name="product_1">
<option value="volvo">Volvo</option>
<option value="saab">Saab</option>
<option value="opel">Opel</option>
<option value="audi">Audi</option>
</select>
</div>
<input id="add_option" type="submit" value="Add More" onclick="return false" />
You can keep appending to the div and the button will still be below it.
I created fiddle for this question.You can create different name according to product group ID.
$(function(){
var productGroupID=1;
$('#add_option').on('click',function(){
productGroupID+=1;
var r= $('<select class="offerte_product" name=product_'+productGroupID+'> <option value="volvo">Volvo</option> </select> ');
$("#dropdown_item").append(r);
});
});
https://jsfiddle.net/ypaudyal/15jt7tLf/
But If you are posting to the server, I suggest you to use same name and collect the selected values in collection.

Change visibility of forms depending on chosen option

I'm making a research form which will display differently depending on the choice of a SELECT value. I have applied some jQuery tricks after searching through here. Unfortunately, it doesn't work at all. Here is my code:
HTML:
<select name="options" id="choice">
<option value="0" selected="true">Choose...</option>
<optgroup label='ABC'>
<option value="1">...DEF</option>
<option value="2">...GHL</option>
</optgroup>
<optgroup label="MNP:">
<option value="3">X</option>
<option value="4">Y</option>
<option value="5">Z</option>
</optgroup>
</select>
<form id="opt1" name="opt1" style="display: none">11111111</form>
<form id="opt2" name="opt2" style="display: none">22222222</form>
<form id="opt3" name="opt3" style="display: none">33333333</form>
<form id="opt4" name="opt4" style="display: none">44444444</form>
<form id="opt5" name="opt5" style="display: none">55555555</form>
JavaScript:
$("#choice").change(function() {
$("form").hide();
$("#opt" + $(this).val()).show();
});
Try this one
$(document).ready(function(){
$('select').change(function() {
//var selected = $(':selected', this);
//alert(selected.closest('optgroup').attr('label'));
$("form").hide();
$("#opt" + $(this).val()).show();
});
});
DEMO here
A #guradio suggests, the code works fine in fiddle. To debug the issue try putting alerts or console.log() to know that the issue it. Hope you have the jQuery library added to your page.
Try these:
$("#choice").change(function() {
alert('fine till here');
$("form").hide();
$("#opt" + $(this).val()).show();
});
Your code is working,I think you are missing j query library on form. please add.
see jsfiddle.net/f5xuc0gh/

How can I insert a variable into the resulting url parameter string after submitting my GET form?

I have a form that queries a library database on another site. It works perfectly if I only include input fields for the "format" and "keyword" because the resulting parameters passed to the url come out in the correct order and the destination site recognizes it.
However, I also need my form to have an input field to select to search by "Author", "Title", "Subject" etc. This is what causes the problem. The destination site only recognizes this parameter if it is in the middle of the url (inside the keyword parameter).
My current resulting url:
http://alpha2.suffolk.lib.ny.us/search~S50/X?SEARCH=harry&searchscope=50&SORT=D&m=b
What I need the url to look like:
http://alpha2.suffolk.lib.ny.us/search~S50/X?SEARCH=t:(harry)&searchscope=50&SORT=D&m=b
If you compare the two you will notice a couple differences. First, ignore the parentheses around harry. That doesn't make a difference. The real issue is how do I get the "t:" to be inserted into my url? The "t:" comes from selecting "Title" as the thing to search by.
Here is my current form HTML (If you remove the "searchtype" select box at the bottom the form will execute without errors, but I need it to execute with it.)
<form class="form-inline" role="search" method="get" name="searchform" id="searchform" action="http://alpha2.suffolk.lib.ny.us/search~S50/X">
<div class="form-group" style="float: left; margin-top: 6px;">
<label class="form-title">Search Collection</label>
</div>
<div class="form-group">
<input type="text" value="" name="SEARCH" id="SEARCH" placeholder="Enter Search Terms..." />
<input type="hidden" value="50" name="searchscope" />
<input type="hidden" value="D" name="SORT" />
</div>
<div class="form-group" style="float: left; margin-top: 3px;">
<label for="searchformat">For:</label>
<select name="m" id="m">
<option value="">ANY</option>
<option value="a">BOOK</option>
<option value="e">EBOOK DOWNLOAD</option>
<option value="l">LARGE PRINT BOOK</option>
<option value="b">BLU-RAY</option>
<option value="g">DVD</option>
<option value="i">AUDIO BOOK CD</option>
<option value="h">AUDIO BOOK MP3CD</option>
<option value="x">EAUDIOBOOK DOWNLOAD</option>
<option value="q">PLAYAWAY</option>
<option value="j">MUSIC CD</option>
<option value="p">MAGAZINE/NEWSPAPER</option>
<option value="n">EMAGAZINE DOWNLOADS</option>
<option value="v">PLAYAWAY VIEW</option>
<option value="s">VIDEO GAME</option>
<option value="r">CD-ROM</option>
<option value="d">VHS</option>
<option value="t">GAMES/PUZZLES</option>
<option value="f">DIGITAL IMAGE</option>
<option value="z">EVIDEO DOWNLOADS</option>
<option value="y">EMUSIC DOWNLOADS</option>
<option value="c">SHEET MUSIC</option>
<option value="m">MAP</option>
<option value="w">ONLINE RESOURCE</option>
<option value="o">OTHER MATERIALS</option>
</select>
</div>
<div class="form-group" style="float: left; margin-top: 3px;">
<label for="searchtype">By:</label>
<select name="" id="searchtype">
<option value="a:"> Author</option>
<option value="t:"> Title</option>
<option value="d:"> Subject</option>
<option value="N:"> Note</option>
<option value="" selected="selected"> Keyword</option>
</select>
</div>
<button class="btn btn-primary" id="searchsubmit" type="Submit">GO</button>
</form>
EDIT:
The attempted Javascript (as requested in the comments):
<script>
function searchSubmit() {
m = document.getElementById("m").value;
t = document.getElementById("searchtype").value;
a = document.getElementById("searcharg").value;
var newurl = "alpha2.suffolk.lib.ny.us/search/X~S22?SEARCH="; + t + a + "&searchscope=50&SORT=D&m=" + m;
var searchform = document.getElementById("searchform");
searchform.action = newurl; searchform.submit();
}
</script>
What I would do is get the searchtype-value and add it to the input-search before submitting. Here is a JS-fiddle example:
$(document).ready(function(){
$("#searchform").on("submit", function(e){
var keyWord = $("#SEARCH").val();
var searchtype = $("#searchtype").val();
$("#SEARCH").val(searchtype + keyWord);
});
});
If you want to use the JavaScript approach, you will have to use AJAX and prevent the default behavior of the button.
document.getElementById("searchsubmit").addEventListener("click", function(event){
event.preventDefault();
var xhttp = new XMLHttpRequest();
//here you set up your variables. One example is
var mysearch = "SEARCH=" + document.getElementById("searchtype").value + document.getElementById("SEARCH").value;
xhttp.open("GET", "yourURL?" + yourVariables, true);
xhttp.send();
});

Trying to redirect with javascript

I'm very new to javascript and I'm trying to make different events occur depending on types of input. I have the following in my html header:
<script type="text/javascript">
function validateForm(){
var val=document.getElementsByName("destination");
if (val == "deprecated"){
window.location="http://website.com/";
}
}
</script>
Then in the body, I have the following:
<select name="destination">
<option value="current_builds">Current Builds</option>
<option value="deprecated">Deprecated Files</option>
<option value="mailing_list">Mailing List</option>
</select><br/>
<input type="button" value="next >" onClick="validateForm()" />
This however doesn't do anything. It just stays on the same page. I also tried wrapping it inside a form tag by saying:
<form name="my_form" onSubmit="validateForm()">
...
</form>
and then having matching javascript:
var val = document.forms["my_form"]["destination"].value
But this didn't work either.
Anyone see what the issue is?
Thanks.
I fixed your function and tested it:
function validateForm(){
var val=document.getElementsByName("destination");
var theSelectedOption = val[0].options[val[0].selectedIndex].value;
if (theSelectedOption == "deprecated"){
window.location="http://website.com/";
}
}
You need to grab the value from the selected element. Since document.getElementsByName returns an array, try using this
var val = ​document.getElementsByName("destination")​​​​​[0].value
You need to get the value from the selected option. Like so:
var index = document.getElementsByName("destination").selectedIndex;
var val=document.getElementsByName("destination").options[index].value;
That will retrieve the value of the selected option.
You're missing the href attribute, you want to use:
window.location.href = 'URL';
do the following
<select name="destination" id="destination">
Your JavaScript
val=document.getElementsById("destination").value;
Put an alert(val) in your if to see if ever evaluates to true
Try this with a little bit of jquery
Redirect using drop down
<form name="my_form">
<select id="destination">
<option value="current_builds">Current Builds</option>
<option value="deprecated">Deprecated Files</option>
<option value="mailing_list">Mailing List</option>
</select><br/>
<input type="button" value="next >" id="submit">
</form>
​
$('#submit').click(
function validateForm(){
var e = document.getElementById("destination");
var val = e.options[e.selectedIndex].value;
if (val == "deprecated"){
window.location="http://website.com/";
}
});
Try it with id's instead of name, an id is a unique element. Javascript supports
var destination = document.getElementById("destination");
if (destination.options[destination.selectedIndex].value == "deprecated"){
window.location="http://website.com/";
}
HTML
<select id="destination">
<option value="current_builds">Current Builds</option>
<option value="deprecated">Deprecated Files</option>
<option value="mailing_list">Mailing List</option>
</select>
<br />
<input type="button" value="next >" onclick="javascript:validateForm();" />

Categories